java Web中页面跳转方式之请求转发
1、在一个请求中跨越多个Servlet
2、多个Servlet在一个请求中,他们共享request对象。就是在Servlet01中setAttribute()保存数据在Servlet02中由getAttribute()取出数据
3、在Servlet01转发到Servlet02,那么整个请求都是由Servlet02来完成,Servlet01不再插手
4、Servlet01 包含Servlet02,那么两个Servlet共同完成请求
5、请求转发和请求包含都需要使用一个对象RequestDispatcher。
public class DemoServlet01 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //从数据库获取数据 UserService service = new UserService(); List<User> userList = service.getUserList(); //把数据放到request对象中 request.setAttribute("userList", userList); //获取重定向对象 RequestDispatcher requestDispatcher = request.getRequestDispatcher("/DemoServlet03"); //重定向对象执行操作 requestDispatcher.forward(request, response); } }
Servlet02:
public class DemoServlet02 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //从request中取出数据 List<User> list = (List<User>) request.getAttribute("userList"); //响应到请求的客户端 response.setContentType("text/html;charset=utf-8"); for (User user : list) { response.getWriter().print(user); } } }
附图一张:
js页面跳转: window.open(url); location.href=url