zoukankan      html  css  js  c++  java
  • [Question] What's the difference between "redirect" & "forward" in servelt?

    Question:

    What's the difference between "redirect" & "forward" in servelt?

    Answer:

    Suppose you have a servlet that just does another redirect to another URL:

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    {
      response.sendRedirect("/anotherURL");
    }
    


    This servlet is accessible through the URL /redirectServlet.

    When the client browser makes a request for /redirectServlet, it receives a response (an HTTP 302 response) that tells it that the document it requested can actually be found at /anotherURL. The client uses the URL it gets and makes a new request to /anotherURL.

    The redirect URL doesn't have to be on the same server as the original URL. If the redirect URL (/anotherURL) points to another servlet, new request and response objects will be created to handle the new request.

    Suppose our redirect servlet is now changed to do a forward instead of a redirect:

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    {
      ServletContext context = getServletContext();
      RequestDispatcher dispatcher = context.getRequestDispatcher("/anotherURL");
      dispatcher.forward(request, response);
    }
    


    This modified servlet is accessible through the URL /forwardServlet.

    When the client makes a request to our forwarding servlet this time, it no longer receives the redirect response. The dispatcher.forward line causes the servlet container to run the servlet associated with the url /anotherURL directly. The client will receive the result of /anotherURL, even though they requested /forwardServlet.

    A few more notes:

    * Redirect is a two step process. The web server tells the browser to request a second URL.
    * If the user reloads, the second URL will be reloaded (/anotherURL instead of /redirectServlet).
    * Redirect is always slower than a forward because it requires a second client request.
    * Attributes placed in the request scope of the redirecting servlet are not available in the request scope of the second rrequest.

    * Forwards are performed internally to the web server.
    * The browser is completely unaware that the forward took place - the original URL (/forwardServlet) remains in the address bar.
    * If the user does a reload, the browser will repeat the original request with the original URL (/forwardServlet).
  • 相关阅读:
    Mybatis plus强大的条件构造器QueryWrapper条件构造器基础方法解释
    代码一键生成
    报错:error setting certificate verify locations: CAfile: D:/Git/anz/Git/mingw64/ssl/certs/ca-bundle.crt CApath: none
    safari怎么设置开发者模式,调出审查元素
    react antd Tabs组件如何修改默认样式-友好的解决方法
    css filter属性滤镜变灰
    yarn的安装和常用命令
    react-app-rewired start 启动失败报错解决方法
    react路由5到底要怎么使用(基础向)
    react中img引入本地图片的2种方式
  • 原文地址:https://www.cnblogs.com/johnny/p/162495.html
Copyright © 2011-2022 走看看