servlet:重定向(客户端跳转)和分发(服务器端跳转)

转发与重定向的区别如下:

转发是服务器行为,重定向是客户端行为

1.转发在服务器端完成的;重定向是在客户端完成的

2.转发的速度快;重定向速度慢

3.转发的是同一次请求;重定向是两次不同请求

4.转发不会执行转发后的代码;重定向会执行重定向之后的代码

5.转发地址栏没有变化;重定向地址栏有变化

6.转发必须是在同一台服务器下完成;重定向可以在不同的服务器下完成

在servlet中调用转发、重定向的语句如下:

request.getRequestDispatcher("new.jsp").forward(request, response);//转发到new.jsp

response.sendRedirect("new.jsp");//重定向到new.jsp

转发过程:客户浏览器发送http请求,web服务器接受此请求,调用内部的一个方法在容器内部完成请求处理和转发动作,将目标资源发送给客户;在这里,转发的路径必须是同一个web容器下的url,其不能转向到其他的web路径上去,中间传递的是自己的容器内的request。在客户浏览器路径栏显示的仍然是其第一次访问的路径,也就是说客户是感觉不到服务器做了转发的。转发行为是浏览器只做了一次访问请求。

重定向过程:客户浏览器发送http请求,web服务器接受后发送302状态码响应及对应新的location给客户浏览器,客户浏览器发现是302响应,则自动再发送一个新的http请求,请求url是新的location地址,服务器根据此请求寻找资源并发送给客户。在这里location可以重定向到任意URL,既然是浏览器重新发出了请求,则就没有什么request传递的概念了。在客户浏览器路径栏显示的是其重定向的路径,客户可以观察到地址的变化的。重定向行为是浏览器做了至少两次的访问请求的。

重定向,其实是两次request

第一次,客户端request A,服务器响应,并response回来,告诉浏览器,你应该去B。这个时候IE可以看到地址变了,而且历史的回退按钮也亮了。重定向可以访问自己web应用以外的资源。在重定向的过程中,传输的信息会被丢失。

1,重定向(客户端跳转):

public class RedirectServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setAttribute("requestKey", "request值");
		HttpSession session=request.getSession();  // 获取session
		session.setAttribute("sessionKey", "session值");
		ServletContext application=this.getServletContext(); // 获取application
		application.setAttribute("applicationKey", "application值");
		response.sendRedirect("target.jsp"); // 客户端跳转/重定向
	}	
}


2,分发(服务器端跳转):

public class ForwardServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setAttribute("requestKey", "request值");
		HttpSession session=request.getSession();  // 获取session
		session.setAttribute("sessionKey", "session值");
		ServletContext application=this.getServletContext(); // 获取application
		application.setAttribute("applicationKey", "application值");
		RequestDispatcher rd=request.getRequestDispatcher("target.jsp");
		rd.forward(request, response); // 服务器调转/转发
	}	
}

猜你喜欢

转载自blog.csdn.net/happydecai/article/details/80308595