【Servlet】服务器内部转发以及客户端重定向

avatar
作者
筋斗云
阅读量:0

文章目录

一、服务器内部转发:request.getRequestDispatcher(“…”).forward(request, response);

一次请求响应的过程,对于客户端而言,内部经过了多少次转发,客户端是不知道的。地址栏中的URL是不会变化的。

内部经过3、4次跳转都是一次请求响应。如图所示:

image-20240402144534703


二、客户端重定向:response.sendRedirect(“×××”);

两次请求响应的过程。客户端肯定知道请求URL有变化。如图所示:

image-20240402144623662


三、服务器内部转发代码示例

服务器内部转发:证明可通过代码断点调试

Demo06Servlet.java

// 演示服务器端内部转发 public class Demo06Servlet extends HttpServlet {     @Override     protected 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 {     @Override     protected 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 {     @Override     protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {         System.out.println("demo06....");         // 客户端重定向         response.sendRedirect("demo07");     } } 

Demo07Servlet.java

public class Demo07Servlet extends HttpServlet {     @Override     protected 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

image-20240305111623108

demo07的状态码则是200

image-20240305111754189

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!