转发和重定向的区别

  • 请求转发:浏览器只发送一次请求,URL不变。
    • 实现原理:由ServletContext在后端实现,会去调用/error对应的servlet的doGet/doPost方法。(通过方法调用实现)
this.getServletContext().getRequestDispatcher("/error").forward(req,resp);

// 常用的是request
req.getRequestDispatcher("/error").forward(req, resp);
  • 重定向:浏览器发送两次请求,URL改变。
    • index.jsp:提交之后,访问/login(Web.xml中映射为RedirectServlet)
      • <html>
        <body>
        <h2>Hello World!</h2>
        
        <form action="${pageContext.request.contextPath}/login" method="get">
            用户名:<input type="text" name="username"> <br>
            密码:<input type="password" name="password"> <br>
            <input type="submit" value="submit">
        </form>
        
        </body>
        </html>
    • RedirectServlet:处理来自form表单的请求。(第二个代码段就是重定向的原理)
      • public class RedirectServlet extends HttpServlet {
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                String username = req.getParameter("username");
                String password = req.getParameter("password");
        
                System.out.println(username + ":" +password);
        
                resp.sendRedirect("/response/success.jsp");
            }
        
            @Override
            protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                this.doGet(req, resp);
            }
        }
        • public class RedirectServlet extends HttpServlet {
              @Override
              protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                  String username = req.getParameter("username");
                  String password = req.getParameter("password");
          
                  System.out.println(username + ":" +password);
          
          //        resp.sendRedirect("/response/success.jsp");
          
                  resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
                  resp.setHeader("Location", "/response/success.jsp");
              }
          
              @Override
              protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                  this.doGet(req, resp);
              }
          }
    • 实现原理:由Tomcat解析HttpServletResponse设置的Status Code和Location。浏览器发现状态码是302时,就知道是重定向,然后重新向Location给定的URL发送请求(相当于JS的window.location)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值