`

web - Forward与Redirect的区别

 
阅读更多

Forward与Redirect

在做前台开发过程中你可能经常遇到关于转发页面得操作,很显然的就想到了forward和redirect,但是到底用哪一个呢,他们之间有什么区别呢,现在我将我自己的理解以及开发的时候怎么应用写出来供大家参考一下:
(1)共同点:
都实现了根据自己的条件实现的页面得跳转。
(2)区别
类别
概念
共享数据
应用
Redirect
URL重新定向:可以是任意的URL
不能共享request里面的数据
一般用于用户注销登录时返回主页面和跳转到其它的网站等等
Forward
页面的转发:只能是同一个Web应用程序的其他Web组件
转发页面和转发到的页面可以共性request里面的数据
一般用于用户登录的时候根据角色转发到相应的模块等等
(3)例子:
譬如:client 通过XXX\index.jsp?name=gauss&pwd=123访问index.jsp,而index.jsp中有<jsp:forward page="login.jsp"/>,则在login.jsp中可以通过request.getParameter()得到name和pwd,而<%response.sendRedirect("login.jsp");%>得不到。
(4) 注意
一般在index.jsp页面之前有个提交数据的页面default.jsp,则defautl.jsp页面提交的数据就可以在login.jsp页面得到,而不是得到index.jsp页面提交的数据,index.jsp页面只是执行的都是一个转发操作当然在里面可以增加也写业务操作,他可以得到request的数据,用XXX\index.jsp?name=gauss&pwd=123这种方式登录就是省略了index.jsp前面的一个页面提交数据而已
 
 
 
 
 

前者仅是容器中控制权的转向,在客户端浏览器地址栏中不会显示出转向后的地址;后者则是完全的跳转,浏览器将会得到跳转的地址,并重新发送请求链接。这样,从浏览器的地址栏中可以看到跳转后的链接地址。所以,前者更加高效,在前者可以满足需要时,尽量使用forward()方法,并且,这样也有助于隐藏实际的链接。在有些情况下,比如,需要跳转到一个其它服务器上的资源,则必须使用

sendRedirect()方法。

forward是服务器请求资源,服务器直接访问目标地址的URL,把那个URL的响应内容读取过来,然后把这些内容再发给浏览器,浏览器根本不知道服务器发送的内容是从哪儿来的,所以它的地址栏中还是原来的地址。

redirect就是服务端根据逻辑,发送一个状态码,告诉浏览器重新去请求那个地址,一般来说浏览器会用刚才请求的所有参数重新请求,所以session,request参数都可以获取

 

原文 : http://blog.sina.com.cn/s/blog_8df07b6f0100u0d1.html

http://www.jq-school.com/Show.aspx?id=270

 

forward 和redirect

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 跳转 redirectforward跳转的区别

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)

...

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

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

来自:http://wenku.baidu.com/link?url=Z8dLJDFT1MX6-yDqajj71B3rc32Zx79iybgSkMoqg922FApVCTviGuYhflaWUiaMYhcAc-It1pKKq2Y127JCYp41U_y4sNsVpQ8AJ_vaEvS

 

分享到:
评论

相关推荐

    forward与redirect区别

    forward是服务器请求资源,服务器直接访问目标地址的URL,把那个URL的响应内容读取过来,然后把这些内容再发给浏览器,浏览器根本不知道服务器发送的内容是从哪儿来的,所以它的地址栏中还是原来的地址。还有,转发...

    Java通用代码生成实用程序XDoclet(源码包)

    redirect="false" /&gt; 例如 model(与数据库中的表对应)类 …… /** * @author yangjuqi 2007-07-18 * * @hibernate.class table="LGS_INVITED_CARRIER" */ public class InvitedCarrierModel ...

    将properties文件的配置设置为整个Web应用的全局变量实现方法

    1、pageContext:页面域,仅当前页面有效,离开页面后,不论重定向还是转向(即无论是redirect还是forward),pageContext的属性值都失效; 2、request:请求域,在一次请求中有效,如果用forward转向,则下一次请求...

    servlet2.4doc

    forward(ServletRequest, ServletResponse) - Method in interface javax.servlet.RequestDispatcher Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. ...

    Java面试宝典-经典

    6、SERVLET API中forward() 与redirect()的区别? 86 7、什么情况下调用doGet()和doPost()? 86 8、Request对象的主要方法: 87 9、forward 和redirect的区别 87 10、request.getAttribute() 和 request....

    javaweb转发和重定向

    javaweb请求转发的简单实例,演示了forward()方法和getRequestDispatcher()的不同之处

    php.ini-development

    You can redirect all of the output of your scripts to a function. For ; example, if you set output_handler to "mb_output_handler", character ; encoding will be transparently converted to the ...

    千方百计笔试题大全

    174、JAVA SERVLET API中forward() 与redirect()的区别? 42 178、如何现实servlet的单线程模式 42 179、页面间对象传递的方法 42 180、JSP和Servlet有哪些相同点和不同点,他们之间的联系是什么? 42 181、四种会话...

    java面试宝典

    187、JAVA SERVLET API中forward() 与redirect()的区别? 44 189、Can a Java Thread be started from Servlet class, and what will be the implications? 45 190、What is ...

    Spring-Reference_zh_CN(Spring中文参考手册)

    12.5.1. iBATIS 1.x和2.x的概览与区别 12.5.2. iBATIS SQL Maps 1.x 12.5.2.1. 创建SqlMap 12.5.2.2. 使用 SqlMapTemplate 和 SqlMapDaoSupport 12.5.3. iBATIS SQL Maps 2.x 12.5.3.1. 创建SqlMapClient 12.5.3.2....

    java面试题,180多页,绝对良心制作,欢迎点评,涵盖各种知识点,排版优美,阅读舒心

    【WEB】转发(forward)和重定向(redirect)的区别 38 forward(转发): 38 redirect(重定向): 39 区别: 39 【WEB】实现会话跟踪的技术有哪些? 40 【WEB】什么是ORM 42 【反射】反射中,Class.forName和...

    Java面试宝典2010版

    6、SERVLET API中forward() 与redirect()的区别? 86 7、什么情况下调用doGet()和doPost()? 8、Request对象的主要方法: 87 9、forward 和redirect的区别 10、request.getAttribute() 和 request.getParameter() ...

    秒杀系统java实现

    //WEB-INF/jsp/"list".jsp } @RequestMapping(value = "/{seckillId}/detail",method = RequestMethod.GET) public String detail(@PathVariable("seckillId") Long seckillId, Model model){ if (seckillId ==...

    史上最全java面试,103项重点知识,带目录

    80. forward 和 redirect 的区别? 39 81. 简述 tcp 和 udp的区别? 40 82. tcp 为什么要三次握手,两次不行吗?为什么? 40 84. OSI 的七层模型都有哪些? 42 85. get 和 post 请求有哪些区别? 42 86. 如何实现...

    最新Java面试宝典pdf版

    6、SERVLET API中forward() 与redirect()的区别? 86 7、什么情况下调用doGet()和doPost()? 86 8、Request对象的主要方法: 87 9、forward 和redirect的区别 87 10、request.getAttribute() 和 request....

    Java面试笔试资料大全

    6、SERVLET API中forward() 与redirect()的区别? 86 7、什么情况下调用doGet()和doPost()? 86 8、Request对象的主要方法: 87 9、forward 和redirect的区别 87 10、request.getAttribute() 和 request....

    java基础题 很全面

    7. forward 和redirect的区别 17 8. 说出在JSP页面里是怎么分页的? 17 9. 什么情况下调用doGet()和doPost()? 17 10. servlet的生命周期 17 11. Servlet执行时一般实现哪几个方法? 17 12. Servlet和CGI的区别。 18 13...

    JAVA面试宝典2010

    6、SERVLET API中forward() 与redirect()的区别? 86 7、什么情况下调用doGet()和doPost()? 86 8、Request对象的主要方法: 87 9、forward 和redirect的区别 87 10、request.getAttribute() 和 request....

    java面试题

    forward和redirect的区别? 答:forward是转发,浏览器跳转后不显示新的地址。 redirect是重定向,浏览器跳转后显示新的地址。 对比之下forward更加高效,并且它有助于隐藏实际地址,但是有些情况则必须使用...

Global site tag (gtag.js) - Google Analytics