javaweb学习12:Response重定向


javaweb学习12:Response重定向

  • Response实现重定向:

    • B一个web资源收到客户端A请求后,B它会通知客户端A去访问另外一个web资源C,这个过程叫重定向;

    • void sendRedirect(String var1) throws IOException;

 

  • 重定向和跳转的区别:

 

  • 常见场景:

    • 用户登录;

 

  • 面试题:请你聊聊重定向和转发的区别:

    • 相同点:

      • 页面都会实现跳转;

    • 不同点:

      • 转发:请求转发的时候,URL不会产生变化;307

      • 重定向:请求转发的时候,URL会发送变化;302

 

 

  • 代码案例:

    ?
    /**
    * 重定向
    */
    public class RedirectServlet extends HttpServlet {
    ?
       @Override
       protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ?
           /*resp.setHeader("Location","/response_war/image");
           resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);*/
           resp.sendRedirect("/response_war/image");//重定向
    ?
      }
    ?
       @Override
       protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           doGet(req, resp);
      }
    }
    ?

     

 



 

  • 重定向:页面间跳转:

    • 重定向一定要注意:路径问题,否则一定会404;

 

  • 代码案例:

    ?
    public class RequestTest extends HttpServlet {
    ?
       @Override
       protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ?
           //处理请求
           String username = req.getParameter("username");
           String pwd = req.getParameter("pwd");
    ?
           System.out.println("username:"+username+";pwd:"+pwd);
           //重定向一定要注意:路径问题,否则一定会404
           resp.sendRedirect("/response_war/success.jsp");
    ?
    ?
      }
    ?
       @Override
       protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           doGet(req, resp);
      }
    }
    ?

     

  • 代码案例:

    <html>
    <head>
       <title>successtitle>
    head>
    <body>
    <h1>Successh1>
    body>
    html>
    ?

     

  • 代码案例:

    <html>
    <head>
       <title>Titletitle>
    head>
    <body>
    <h2>Hello ,world h2>
    ?
    <%--
       这里提交的路径:需要寻找到项目的路径
       ${pageContext.request.contextPath}:代表当前的项目
    ?
    --%>
    <form action="${pageContext.request.contextPath}/login" method="get">
      用户名:<input type="text"name="username"><br/>
      密码:  <input type="password" name="pwd">
    ?
       <input type="submit"/>
    form>
    ?
    ?
    body>
    html>
    ?