文章目录
- 一、服务器内部转发:request.getRequestDispatcher("...").forward(request, response);
- 二、客户端重定向:response.sendRedirect("×××");
- 三、服务器内部转发代码示例
- 四、客户端重定向代码示例
一、服务器内部转发:request.getRequestDispatcher(“…”).forward(request, response);
一次请求响应的过程,对于客户端而言,内部经过了多少次转发,客户端是不知道的。地址栏中的URL是不会变化的。
内部经过3、4次跳转都是一次请求响应。如图所示:
二、客户端重定向:response.sendRedirect(“×××”);
两次请求响应的过程。客户端肯定知道请求URL有变化。如图所示:
三、服务器内部转发代码示例
服务器内部转发:证明可通过代码断点调试
Demo06Servlet.java
// 演示服务器端内部转发
public class Demo06Servlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("demo06....");// 服务器端内部转发request.getRequestDispatcher("demo07").forward(request, response);}
}
Demo07Servlet.java
public class Demo07Servlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("demo07....");}
}
web.xml
<servlet><servlet-name>Demo06Servlet</servlet-name><servlet-class>com.atguigu.servlets.Demo06Servlet</servlet-class>
</servlet>
<servlet-mapping><servlet-name>Demo06Servlet</servlet-name><url-pattern>/demo06</url-pattern>
</servlet-mapping><servlet><servlet-name>Demo07Servlet</servlet-name><servlet-class>com.atguigu.servlets.Demo07Servlet</servlet-class>
</servlet>
<servlet-mapping><servlet-name>Demo07Servlet</servlet-name><url-pattern>/demo07</url-pattern>
</servlet-mapping>
四、客户端重定向代码示例
Demo06Servlet.java
// 演示服务器端内部转发以及客户端重定向
public class Demo06Servlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("demo06....");// 客户端重定向response.sendRedirect("demo07");}
}
Demo07Servlet.java
public class Demo07Servlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("demo07....");}
}
web.xml
<servlet-mapping><servlet-name>Demo06Servlet</servlet-name><url-pattern>/demo06</url-pattern>
</servlet-mapping><servlet><servlet-name>Demo07Servlet</servlet-name><servlet-class>com.atguigu.servlets.Demo07Servlet</servlet-class>
</servlet>
<servlet-mapping><servlet-name>Demo07Servlet</servlet-name><url-pattern>/demo07</url-pattern>
</servlet-mapping>
访问demo06,一敲回车,可以发现它发送了两次请求
点击demo06的请求,可以发现状态码为302(重定向),Location也变成了demo07
demo07的状态码则是200