一、什么是 请求转发 和 请求重定向?
请求转发:把请求转发给另一个Servlet处理,同时共享request 中的数据(A请求B,B做不了,转给C;C做完给B,B交付给A)
请求重定向:获取请求后,再将请求给另一个Servlet处理(A请求B,B做不了;A又去请求C,C做完交付给A)
二、请求转发 与 请求重定向 有什么区别?
本质区别:请求转发只是发送了一次请求,请求重定向发送了两次请求
请求转发:
- 地址栏初次请求的url
- 在最终的Servlet中,request对象和中转的request对象是同一个对象
- “/”代表当前web应用的根目录http://localhost:8080/002ServletTest--这是当前web应用的根目录
- 只能转到当前web资源
请求重定向:
- 地址栏不是最初的url,而且最后一次响应的url
- 在最终的Servlet中,request对象和中转的request对象是不同一个对象
- “/”代表当前web站点的根目录http://localhost:8080--这是当前web站点
- 可以重定向到外部资源
三、例:
请求转发:
@WebServlet("/forWardServlet")
public class ForWard extends HttpServlet {
private static final long serialVersionUID = 1L;
public ForWard() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//请求转发:把请求转发给另一个Servlet处理
System.out.println("forWardServlet..");
//setAttribute方法:向域对象中添加值
request.setAttribute("name", "zhangsan");
//请求转发的地址
String path = "/testServlet";
//请求转发
request.getRequestDispatcher(path).forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
@WebServlet("/testServlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//打印
System.out.println("testServlet...");
//打印Request中的值,证明是否共享request
System.out.println(request.getAttribute("name"));
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
结果为:
请求重定向:
@WebServlet("/redirceServlet")
public class RedirceServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RedirceServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("redirceServlet...");
//重定向
response.sendRedirect("testServlet");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
@WebServlet("/testServlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//打印
System.out.println("testServlet...");
//打印Request中的值,证明是否共享request
System.out.println(request.getAttribute("name"));
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
结果为: