一、调用方式

我们知道,在servlet中调用转发、重定向的语句如下:

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

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

在jsp页面中你也会看到通过下面的方式实现转发:

<jsp:forward page="apage.jsp" />

当然也可以在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应用以外的资源。在重定向的过程中,传输的信息会被丢失。

例子:

response.sendRedirect("loginsuccess.jsp");

请求转发是服务器内部把对一个request/response的处理权,移交给另外一个

对于客户端而言,它只知道自己最早请求的那个A,而不知道中间的B,甚至C、D。传输的信息不会丢失。

例子:

RequestDispatcher dis=request.getRequestDispatcher(“loginsuccess.jsp”);

Dis.forward(request,response);

解释三

假设你去办理某个执照

重定向:你先去了A局,A局的人说:“这个事情不归我们管,去B局”,然后,你就从A退了出来,自己乘车去了B局。

转发:你先去了A局,A局看了以后,知道这个事情其实应该B局来管,但是他没有把你退回来,而是让你坐一会儿,自己到后面办公室联系了B的人,让他们办好后,送了过来。

http://blog.163.com/tsing_hua/blog/static/139622224201101110836644/

http://blog.csdn.net/cuiweibing/article/details/1791655

1. forward方法使用

request.getRequestDispatcher(path).forward(request.response);

首先来看getRequestDispatcher方法,path必须是相对路径。

getRequestDispatcher

RequestDispatcher getRequestDispatcher(String path)
Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response. The resource can be dynamic or static.

The pathname specified may be relative, although it cannot extend outside the current servlet context. If the path begins with a "/" it is interpreted as relative to the current context root. This method returns null if the servlet Container cannot return a RequestDispatcher.

The difference between this method and ServletContext.getRequestDispatcher(java.lang.String) is that this method can take a relative path.

Parameters:
path - a String specifying the pathname to the resource. If it is relative, it must be relative against the current servlet.
Returns:
RequestDispatcher object that acts as a wrapper for the resource at the specified path, or null if the servlet container cannot return a RequestDispatcher
See Also:
RequestDispatcherServletContext.getRequestDispatcher(java.lang.String)

接着forward方法,

forward

void forward(ServletRequest request,
ServletResponse response)
throws ServletException,
IOException
Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. This method allows one servlet to do preliminary processing of a request and another resource to generate the response.

For a RequestDispatcher obtained via getRequestDispatcher(), the ServletRequest object has its path elements and parameters adjusted to match the path of the target resource.

forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.

The request and response parameters must be either the same objects as were passed to the calling servlet's service method or be subclasses of theServletRequestWrapper or ServletResponseWrapper classes that wrap them.

Parameters:
request - a ServletRequest object that represents the request the client makes of the servlet
response - a ServletResponse object that represents the response the servlet returns to the client
Throws:
ServletException - if the target resource throws this exception
IOException - if the target resource throws this exception
IllegalStateException - if the response was already committed

2.sendRedirect方法使用

HttpServletResponse中使用sendRedirect可以实现跳转,可以接受相对路径或者绝对路径。

sendRedirect

public void sendRedirect(java.lang.String location)
throws java.io.IOException
Sends a temporary redirect response to the client using the specified redirect location URL. This method can accept relative URLs; the servlet container must convert the relative URL to an absolute URL before sending the response to the client. If the location is relative without a leading '/' the container interprets it as relative to the current request URI. If the location is relative with a leading '/' the container interprets it as relative to the servlet container root.

If the response has already been committed, this method throws an IllegalStateException. After using this method, the response should be considered to be committed and should not be written to.

参数
定位 - the redirect location URL
Throws:
java.io.IOException - If an input or output exception occurs
java.lang.IllegalStateException - If the response was committed or if a partial URL is given and cannot be converted into a valid URL

Servlet 跳转 redirect与forward跳转的区别

Servlet:

当然,在servlet中,一般跳转都发生在doGet, doPost等方法里面。

一、原理

1) redirect 方式

response.sendRedirect("/a.jsp");

页面的路径是相对路径。sendRedirect可以将页面跳转到任何页面,不一定局限于本web应用中,如:

response.sendRedirect("http://www.ycul.com");

跳转后浏览器地址栏变化。

这种方式要传值出去的话,只能在url中带parameter或者放在session中,无法使用request.setAttribute来传递。

这种方式是在客户端作的重定向处理。该方法通过修改HTTP协议的HEADER部分,对浏览器下达重定向指令的,让浏览器对在location中指定的URL提出请求,使浏览器显示重定向网页的内容。该方法可以接受绝对的或相对的URLs。如果传递到该方法的参数是一个相对的URL,那么Web container在将它发送到客户端前会把它转换成一个绝对的URL。public void doPost(HttpServletRequest request,HttpServletResponse response)    throws ServletException,IOException

{

response.setContentType("text/html; charset=UTF-8");

response.sendRedirect("/index.jsp");

}

2) forward方式

RequestDispatcher dispatcher = request.getRequestDispatcher("/a.jsp");

dispatcher .forward(request, response);

页面的路径是相对路径。forward方式只能跳转到本web应用中的页面上。

跳转后浏览器地址栏不会变化。

使用这种方式跳转,传值可以使用三种方法:url中带parameter,session,request.setAttribute

这种方式是在服务器端作的重定向。服务器往client发送数据的过程是这样的:服务器在向客户端发送数据之前,是先将数据输出到缓冲区,然后将缓冲区中数据发送给client端。什么时候将缓冲区里的数据发送给client端呢?(1)当对来自client的request处理完,并把所有数据输出到缓冲区,(2)当缓冲区满,(3)在程序中调用缓冲区的输出方法out.flush()或response.flushbuffer(),web container才将缓冲区中的数据发送给client。

这种重定向方式是利用服务器端的缓冲区机制,在把缓冲区的数据发送到客户端之前,原来的数据不发送,将执行转向重定向页面,发送重定向页面的数据,重定向调用页的数据将被清除。如果在<JSP:FORWORD>之前有很多输出,前面的输出已使缓冲区满,将自动输出到客户端,那么这种重定向方式将不起作用,这一点应该特别注意。

public void doPost(HttpServletRequest request,HttpServletResponse response)   throws ServletException,IOException

{

response.setContentType("text/html; charset=UTF-8");

ServletContext sc = getServletContext();

RequestDispatcher rd = null;

rd = sc.getRequestDispatcher("/index.jsp");

rd.forward(request, response);

}

二、区别.

1、forward重定向是在容器内部实现的同一个Web应用程序的重定向,所以forward方法只能重定向到同一个Web应用程序中的一个资源,重定向后浏览器地址栏URL不变,而sendRedirect方法可以重定向到任何URL, 因为这种方法是修改http头来实现的,URL没什么限制,重定向后浏览器地址栏URL改变。

2、forward重定向将原始的HTTP请求对象(request)从一个servlet实例传递到另一个实例,而采用sendRedirect方式两者不是同一个application。

3、基于第二点,参数的传递方式不一样。forward的form参数跟着传递,所以在第二个实例中可以取得HTTP请求的参数。sendRedirect只能通过链接传递参数,response.sendRedirect(“login.jsp?param1=a”)。

4、sendRedirect能够处理相对URL,自动把它们转换成绝对URL,如果地址是相对的,没有一个‘/’,那么Web container就认为它是相对于当前的请求URI的。比如,如果为response.sendRedirect("login.jsp"),则会从当前servlet 的URL路径下找login.jsp: http://10.1.18.8:8081/dms/servlet/Servlet 重定向的URL: http://10.1.18.8:8081/dms/servlet/login.jsp,如果为response.sendRedirect("/login.jsp")则会从当前应用径下查找url:http://10.1.18.8:8081/login.jsp。而forward不能这样处理相对路径。

Java

他们的区别是:

response.sendRedirect是向客户浏览器发送页面重定向指令,浏览器接收后将向web服务器重新发送页面请求,所以执行完后浏览器的url显示的是跳转后的页面。跳转页面可以是一个任意的url(本服务器的和其他服务器的均可)。

RequestDispatcher.forward则是直接在服务器中进行处理,将处理完后的信息发送给浏览器进行显示,所以完成后在url中显示的是跳转前的页面。在forward的时候将上一页面中传送的request和response信息一同发送给下一页面(而response.sendRedirect不能将上一页面的request和response信息发送到下一页面)。由于forward是直接在服务器中进行处理,所以forward的页面只能是本服务器的。

JSP:

1) response.sendRedirect();

和servlet的response.sendRedirect()方式一样。

此语句前不允许有out.flush(),如果有,会有异常:

java.lang.IllegalStateException: Can't sendRedirect() after data has committed to the client.

at com.caucho.server.connection.AbstractHttpResponse.sendRedirect(AbstractHttpResponse.java:558)

...

跳转后浏览器地址栏变化

如果要跳到不同主机下,跳转后,此语句后面的语句会继续执行,如同新开了线程,但是对response的操作已经无意义了;

如果要跳到相同主机下,此语句后面的语句执行完成后才会跳转;

2) response.setHeader("Location","");

此语句前不允许有out.flush(),如果有,页面不会跳转。

跳转后浏览器地址栏变化

此语句后面的语句执行完成后才会跳转

3) <jsp:forward page="" />

此语句前不允许有out.flush(),如果有,会有异常:

java.lang.IllegalStateException: forward() not allowed after buffer has committed.

at com.caucho.server.webapp.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:134)

at com.caucho.server.webapp.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:101)

at com.caucho.jsp.PageContextImpl.forward(PageContextImpl.java:836)

...

跳转后浏览器地址栏不变,但是只能跳到当前主机下

此语句后面的语句执行完成后才会跳转

jsp中forward与redirect的更多相关文章

  1. JSP 中 forward 和 redirect 的区别_2014.12.31

    重定向,只能访问工程下(WebRoot文件夹)的页面,不能访问到内部(WEB_INF文件夹)的页面 1.从地址栏显示来说:forward浏览器显示路径不变,redirect浏览器显示路径改变forwa ...

  2. jsp中forward和redirect的区别(转)

    一.调用方式 我们知道,在servlet中调用转发.重定向的语句如下: request.getRequestDispatcher("new.jsp").forward(reques ...

  3. Servlet中forward和redirect的区别(转)

    forward方式:request.getRequestDispatcher("/somePage.jsp").forwardrequest, response);     red ...

  4. springmvc中forward和redirect

    一.跳转 import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; im ...

  5. Servlet中forward和redirect的区别

    forward方式:request.getRequestDispatcher("/somePage.jsp").forwardrequest, response);      re ...

  6. SERVLET API 中 forward() 与 redirect()的区别?

    答:前者仅是容器中控制权的转向, 在客户端浏览器地址栏中不会显示出转向后的地址: 后者则是完全的跳转, 浏览器将会得到跳转的地址, 并重新发送请求链接. 这样, 从浏览器的地址栏中可以看到跳转后的链接 ...

  7. SERVLET API中forward()与redirect()的区别?

    前者仅是容器中控制权的转向,在客户端浏览器地址栏中不会显示出转向后的地址:后者则是完全的跳转,浏览器将会得到跳转的地址,并重新发送请求链接.这样,从浏览器的地址栏中可以看到跳转后的链接地址.所以,前者 ...

  8. jsp中jsp:forward 与 redirect区别

    部分转载:http://hi.baidu.com/168zlf/item/2f4b2ad4351b881c20e2500c 在网上看到一些帖子,总结了一些区别,可以从以下几个方面来看: 1.从地址栏显 ...

  9. jsp中的forward和redirect的区别

    转自http://blog.163.com/tsing_hua/blog/static/139622224201101110836644/ 一.调用方式 我们知道,在servlet中调用转发.重定向的 ...

随机推荐

  1. http与rfc

    超文本传输协议(HTTP,HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络协议.所有的WWW文件都必须遵守这个标准.设计HTTP最初的目的是为了提供一种发布和接 ...

  2. Charles 抓包工具

    参考博客: https://blog.csdn.net/mxw2552261/article/details/78645118 发包与改包: https://blog.csdn.net/b722305 ...

  3. Java反序列化漏洞实现

    一.说明 以前去面试被问反序列化的原理只是笼统地答在参数中注入一些代码当其反序列化时被执行,其实“一些代码”是什么代码“反序列化”时为什么就会被执行并不懂:反来在运营商做乙方经常会因为java反反序列 ...

  4. Linux---centos编译安装ffmpeg

    环境 系统环境:CentOS release 6.7 (Final) 需求 编译安装ffmpeg 获取依赖 安装依赖包 yum install -y autoconf automake cmake f ...

  5. Linux中的#和$区别

    [#]代表 root权限[$]代表普通用户

  6. redis-sentinel主从复制高可用

    Redis-Sentinel Redis-Sentinel是redis官方推荐的高可用性解决方案,当用redis作master-slave的高可用时,如果master本身宕机,redis本身或者客户端 ...

  7. chrome扩展应用实例

    chrome extensions 基本组成,唯一必要的文件就是manifest.json这个应用的配置清单 manifest.json中前三个参数为必要参数,其他的可选: { "name ...

  8. python如何实现像shell中的case功能

    我们知道在shell脚本里是支持case语句,当位置参数为空时,会提示我们怎么使用脚本 那么在python怎么实现呢?也使用case吗? python里不支持case语句,但是也有实现case的方法. ...

  9. copy GC 和 mark & compaction GC的算法异同

    先标记 然后 copy GC是,对所有child,判断, 如果child没有被访问过,那么拷贝到新地址,child的forwording指向新地址,child标记为已访问,把自己对child的引用改为 ...

  10. 5.移动终端App测试点归纳

    以下所有测试最后必须在真机上完整的执行. 1 安装.卸载测试 1.1 在真机上.第三方软件(xy苹果助手.91.安卓助手)的安装与卸载 1.2 安装在手机卡上 或 SD卡上 (不同的IOS和安卓版本) ...