getRequestDispatcher 和sendRedirect区别
getRequestDispatcher是服务器内部跳转,地址栏信息不变,只能跳转到web应用内的网页。
sendRedirect是页面重定向,地址栏信息改变,可以跳转到任意网页。
这两条网上都查得到,但看着比较乱,现提供我测试的结果(仅供参考):
1.getRequestDispatcher分成两种,可以用request调用,也可以用getServletContext()调用
不同的是request.getRequestDispatcher(url)的url可以是相对路径也可以是绝对路径。
而this.getServletContext().getRequestDispatcher(url)的url只能是绝对路径。
SecondServlet request.setAttribute("lover", "tom"); request.getSession().setAttribute("lovered", "joe"); request.getRequestDispatcher("/third?name=jay").forward(request, response); 或 request.getRequestDispatcher("third?name=jay").forward(request, response); 或 this.getServletContext().getRequestDispatcher("/third?name=jay").forward(request, response);
ThirdServlet PrintWriter out = response.getWriter(); String name = request.getParameter("name"); out.println(request.getContextPath()+"<hr/>"); out.println("name="+name+"<hr/>"); out.println("lover="+request.getAttribute("lover")+"<hr/>"); out.println("lovered="+request.getSession().getAttribute("lovered")+"<hr/>");
SecondServlet request.setAttribute("lover", "tom"); request.getSession().setAttribute("lovered", "joe"); response.sendRedirect("third?name=jay"); 或 response.sendRedirect(request.getContextPath()+"/third?name=jay");
ThirdServlet PrintWriter out = response.getWriter(); String name = request.getParameter("name"); out.println(request.getContextPath()+"<hr/>"); out.println("name="+name+"<hr/>"); out.println("lover="+request.getAttribute("lover")+"<hr/>"); out.println("lovered="+request.getSession().getAttribute("lovered")+"<hr/>");
response.sendRedirect("http://www.baidu.com");