请求转发与重定向
一.请求转发
请求转发地址栏不变,这是一次请求
请求转发是服务器内部行为
当做域对象使用,即相当于容器,可以装载数据
两个servlet中请求域数据在一次请求转发中==共享==
doGet()只能向另外一个Servlet的doGet()方法中进行请求转发,doPost()同理,否则报错:
HTTP Status 405 - HTTP method GET is not supported by this URL,如图所示:
@WebServlet("/ser1")
public class DispatcherServlet1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("1 接收请求");
System.out.println("2 调用业务层处理数据");
System.out.println("3 进行重定向页面跳转");
//向请求域中存入数据 【name:张三】
req.setAttribute("name", "张三");
req.getRequestDispatcher("/ser2").forward(req, resp);
}
}
@WebServlet("/ser2")
public class DispatcherServlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//查看重定向是否可以取出请求域中的数据
Object name = req.getAttribute("name");
System.out.println(name);
System.out.println("4 重定向跳转成功");
}
}
/**
控制台输出内容:
1 接收请求
2 调用业务层处理数据
3 进行重定向页面跳转
张三
4 重定向跳转成功
*/
浏览器端行为:
二.重定向
- 重定向是响应重定向,是浏览器行为
- 两次请求
- 地址栏会变化
- 请求域数据无法共享
@WebServlet("/ser1")
public class DispatcherServlet1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("1 接收请求");
System.out.println("2 调用业务层处理数据");
String contextPath = req.getContextPath();
System.out.println(contextPath);
resp.sendRedirect(contextPath + "/ser2");
}
}
@WebServlet("/ser2")
public class DispatcherServlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object name = req.getAttribute("name");
System.out.println(name);
System.out.println("3 查询数据");
}
}
//控制台输出内容
/**
1 接收请求
2 调用业务层处理数据
3 进行重定向页面跳转
null
4 重定向跳转成功
*/
浏览器行为: