一. 概念
- redirect(从定向):客户端发送一个redirect请求的时候,服务端回复给客户端一个重定向的临时响应头,这个响应头包含重定向之后的URL,客户端用新的URL(参数丢失)重新向URL对应服务器发送一个请求。
- forward(转发):客户端发送一个forward请求的时候,服务器内部完成转发(参数仍在这个request里面),把转发之后的结果回复给客户端。
- 区别:
- 请求转发,即(一次请求,保存请求对象)request.getRequestDispatcher().forward(),是一种服务器的行为,客户端只有一次请求,服务器端转发后会将请求对象保存,地址栏中的URL地址不会改变,得到响应后服务器端再将响应发给客户端;
-
请求重定向:
请求重定向,即response.sendRedirect(),是一种客户端行为,从本质上讲等同于两次请求,前一次请求对象不会保存,地址栏的URL地址会改变。
二. Redirect
- HttpServletResponse.sendRedirect(String location)源码
Java代码
- public void sendRedirect(String location) throws IOException {
- if (isCommitted())
- throw new IllegalStateException
- (sm.getString("coyoteResponse.sendRedirect.ise"));
- // Ignore any call from an included servlet
- if (included)
- return;
- // Clear any data content that has been buffered
- resetBuffer();
- // Generate a temporary redirect to the specified location
- try {
- //1.将ocation转换成绝对路径
- String absolute = toAbsolute(location);
- //2.设置新的效应头部302
- setStatus(SC_FOUND);
- //3.设置Location
- setHeader("Location", absolute);
- } catch (IllegalArgumentException e) {
- setStatus(SC_NOT_FOUND);
- }
- // Cause the response to be finished (from the application perspective)
- setSuspended(true);
- }
- 看源码就知道sendRedirect的使用了
- 带http协议的,从定向到指定服务器。
Java代码
- 在http://localhost:8080/CoreServer/page/report/report.jsp页面
- httpServletResponse.sendRedirect("http://www.baidu.com");
- =====>
- http://www.baidu.com。
- 其它类型都跳转到内部服务器。
Java代码
- 在http://localhost:8080/CoreServer/page/report/report.jsp页面httpServletResponse.sendRedirect("www.baidu.com");
- =====>
- http://localhost:8080/CoreServer/page/report/www.baidu.com。
- httpServletResponse.sendRedirect("reportList.jsp);
- =====>
- http://localhost:8080/CoreServer/page/report/reportList.jsp。
- 带http协议的,从定向到指定服务器。
三. forward
- 基于请求路径和转发路径,内部完成跳转。
Java代码
- 在http://localhost:8080/CoreServer/page/report/report.jsp(请求路径)页面HttpServletRequest.getRequestDispatcher("t1.jsp").forward(request, response);(转发路径)
- 返回http://localhost:8080/CoreServer/page/report/t1.jsp的内容。
四. struts规范
- struts.xml文件里,<result>标签的type默认属性值是"dispatcher"(实际上就是转发,forward)。开发人员可以根据自己的需要指定不同的类型,如redirect、stream等。
- servlet 2.4规范,默认forward不经过filter。如果你要让forward的页面也经过filter,web.xml配置如下。
Java代码
- <filter>
- <filter-name>jspFilter</filter-name>
- <filter-class>com.cb.cbms.coreserver.servlet.JspFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>jspFilter</filter-name>
- <url-pattern>/*</url-pattern>
- <dispatcher>REQUEST</dispatcher> //forward要经过哪些filter,在对应filter下面加上这两行
- <dispatcher>FORWARD</dispatcher>
- </filter-mapping>
- 如果在项目里出现了,
Java代码
- 此页面不能正确地重定向
- **浏览器检测到该服务器正在将此地址的请求循环重定向。