Servlet跳转方式sendReDirect()和forward()

在web应用服务中,经常会面对不同SERVLET之间的跳转,目前我们可以通过以下两种方式实现:

1.RequestDispatcher.forward()

2.ServletResponse.sendReDirect()

两者的区别:

1.redirect 方式可以跨应用访问,forward 只能在同一个应用中跳转。

2.forward 客户端访问服务器,服务器找到要跳转的相应URL并执行返回给客户端。客户端的地址栏显示的是原始URL。

   redirect 客户端访问服务器,服务器找到要跳转的URL并将URL发给客户端,再由客户端对新的URL重新发送请求。客

   户端的地址栏显示的是第二次请求的URL。

3.数据的传输:在request中的数据,forward可以访问,redirect不行,因为redirect已经是一个新的请求。

相对路径的理解:

forward中"/"相对于web应用.
http://localhost:8080/Test/gw/page.jsp中转发
  <jsp:forward page="OtherPage.jsp"/>在JSP页面被解析后转换成pageContext.forward("OtherPage.jsp");
  "/OtherPage.jsp"提交到http://localhost:8080/Test/OtherPage.jsp
  "OtherPage.jsp"提交到http://localhost:8080/Test/gw/OtherPage.jsp
  
  <form action="/ddd"> 和 response.sendRedirect("/ddd"); 相对于服务器根路径.
  假设转发代码包含于注册的servlet-url为/ggg/tt;jsp为/ggg/tt.jsp:
  绝对路径:response.sendRedirect("http://www.brainysoftware.com")发送http://www.brainysoftware.com
  根路径:response.sendRedirect("/ooo")发送至http://localhost:8080/ooo
  相对路径:response.sendRedirect("ooo")发送至http://localhost:8080/Test/ggg/ooo

原文地址:https://www.cnblogs.com/qiuhaojie/p/6797117.html