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


转载于:https://www.cnblogs.com/davidwang456/p/3998013.html

forward 和redirect相关推荐

  1. forward和redirect的区别

    2019独角兽企业重金招聘Python工程师标准>>> 1.从地址栏显示来说  forward是服务器请求资源,服务器直接访问目标地址的URL,把那个URL的响应内容读取过来,然后把 ...

  2. forward 和redirect的区别

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

  3. forward、redirect、浏览器的路径问题

    浏览器: 1.路径以"/"开头,浏览器会把http://localhost:8080/作为根目录 <img src="http://images.cnblogs.c ...

  4. forward和redirect有什么区别?

    题目:下面有关forward和redirect的描述,正确的是() ? A.forward是服务器将控制权转交给另外一个内部服务器对象,由新的对象来全权负责响应用户的请求 B.执行forward时,浏 ...

  5. 《Spring实战》读书笔记--SpringMVC之forward与redirect

    <Spring实战>读书笔记--SpringMVC之forward与redirect 1.forward与redirect介绍 1.1 redirect 重定向,服务器收到请求后发送一个状 ...

  6. java中forward和redirect_好程序员Java教程分享:Forward和Redirect的区别

    Java教程分享:Forward和Redirect的区别,用户向服务器发送了一次HTTP请求,该请求可能会经过多个信息资源处理以后才返回给用户,各个信息资源使用请求转发机制相互转发请求,但是用户是感觉 ...

  7. 如何在请求转发的时候对url解码_Java技术分享:Forward和Redirect这两种转发方式的区别...

    用户向服务器发送了一次HTTP请求,该请求可能会经过多个信息资源处理以后才返回给用户,各个信息资源使用请求转发机制相互转发请求,但是用户是感觉不到请求转发的.根据转发方式的不同,可以区分为直接请求转发 ...

  8. Jsp中的forward 和 redirect

    Jsp中的forward 和 redirect 一.绝对路径和相对路径 相对路径 绝对路径 二.实现机制 Forward:转发----服务器行为 Redirect:重定向----客户端行为 三.运用场 ...

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

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

  10. Java Web中Forward和redirect的区别

    导读:Servlet有三种协作方案:Forward协作.Include协作.重定向协议(Redirect). include协作就是一个servlet包含了另一个servlet的全部内容 那么,For ...

最新文章

  1. JQuery.Ajax 错误调试帮助信息
  2. python变量存储 堆与栈内存内存_浅析JS中的堆内存与栈内存
  3. kafka可视化客户端工具(Kafka Tool)的基本使用
  4. ninja: error: 'LIBSOUNDIO_LIB-NOTFOUND', needed by 'bin/k4aviewer', missing and no known rule to mak
  5. for循环与foreach的性能比较
  6. 设计原则(6):开闭原则
  7. 在线客服代码:在线QQ客服、在线旺旺客服
  8. mysql workbench pk_MySQL Workbench筑表时PK, NN, UQ, BIN, UN, ZF, AL的意思
  9. 基于C语言的信息管理系统和小游戏
  10. 第一天Java学习笔记
  11. Word修改默认英文字体为Times New Roman
  12. 【C语言面试复试汇总】
  13. 可动态迁移的 mysql 架构
  14. PMO如何赋能与支撑战略项目管理︱亚马逊PMO负责人宋晓雪
  15. 信号完整性分析与电源完整性分析学习笔记(一)
  16. 关于Mybatis的错误Statement returned more than one row, where no more than one was expected
  17. 文本与文本处理(一)
  18. 如何解决word文档报错打不开呢?
  19. 关于对大一上学期的学习总结及大一下学期的规划。
  20. Oracle JDBC内存管理(Oracle JDBC Memory Management)

热门文章

  1. cumsum在matlab中,matlab中cumsum函数和sum函数详解
  2. linux扫描hba卡命令,如何在redhat中查看HBA卡的信息
  3. 一次性定时事件的处理
  4. 三星手机Android9和10的区别,三星开始在Galaxy Note 9上测试Android 10
  5. python中list[1啥意思_详解Python中list[::-1]的几种用法
  6. python元组支持双向索引吗_2、Python列表和元组
  7. 电脑主板接口_POWER SW、RESET SW、POWER LED、HDD LED电脑主板跳线怎么接?
  8. win服务器自动发邮件,windows关机前执行脚本设置与关机blat自动发送邮件脚本模板...
  9. java使用getinputstream_java解析数据接口获取json对象
  10. android 之图文混排+GridView