1.Forword


request.getRequestDispatcher (“url”).forword (request,response) 是请求转发,也就是说,一个 Servlet 向当前的

Servlet 发出请求后,经过这个方法后,请求会继续转发到请求的 URL, 在这个过程中,只向服务器发出一次请求。效率当然也就高了.
从在浏览器地址栏中显示的 URL 来看,response.sendRedirect (“url”), 地址栏中的 URL 会发生变化,会显示重定向的这个 URL 的地址,
而 request.getRequestDispatcher (“url”).forword (request,response) 这种方法,地址栏中的地址是不变的.
示例如下:
先创建 servlet 实例:a.java 代码如下:

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
package package1;

import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

/** * Servlet implementation class a */@WebServlet("/a")public class a extends HttpServlet {	private static final long serialVersionUID = 1L;

    /**     * @see HttpServlet#HttpServlet()     */    public a() {        super();        // TODO Auto-generated constructor stub    }

	/**	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)	 */	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		// TODO Auto-generated method stub		//第一种 请求转发		request.setAttribute("message","aaaaaa");		request.getRequestDispatcher("/b").forward(request,response);		// 第二种 重定向		response.setContentType("text/html; charset=UTF-8");		response.sendRedirect("/Tomcat_Test/b");	}

	/**	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)	 */	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		// TODO Auto-generated method stub

	}

}

创建 servlet 实例:b.java 代码如下:

1234567891011121314151617181920212223242526272829303132333435363738394041424344
package package1;

import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

/** * Servlet implementation class b */@WebServlet("/b")public class b extends HttpServlet {	private static final long serialVersionUID = 1L;

    /**     * @see HttpServlet#HttpServlet()     */    public b() {        super();        // TODO Auto-generated constructor stub    }

	/**	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)	 */	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		// TODO Auto-generated method stub		response.setCharacterEncoding("utf-8");		String message=(String)request.getAttribute("message");		response.getWriter().append("this is B page with message from A: ").append(message);

	}

	/**	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)	 */	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		// TODO Auto-generated method stub		doGet(request, response);	}

}

先注释

123
// 第二种 重定向response.setContentType("text/html; charset=UTF-8");response.sendRedirect("/Tomcat_Test/b");

运行 a.java 测试 “请求转发”

getRequestDispatcher () 方法的参数必须以 “/” 开始,“/” 表示本 Web 应用程序的根目录。如上例中,表示要跳转的地址为 http://localhost:8080/servlet/b

forward 是最常用的方式,在 Structs 等 MVC 框架中,都是用 Servlet 来处理用户请求,把结果通过 request.setAttribute () 放到 request 中,
然后 forward 到 JSP 中显示。
当执行 forward 方法时,不能有任何输出到达客户端,否则会抛出异常,也就是说,在 forward 之前,不要使用 out.println () 语句向客户端输出。

尤其注意 HttpServlet 默认的 super.doGet () 和 super.goPost () 方法都包含了相关操作,所以在使用时应该把这两个方法注释掉!!

2.Redirect


这种方式要传值出去的话,只能在 url 中带 parameter 或者放在 session 中,无法使用 request.setAttribute 来传递。
这种方式是在客户端作的重定向处理。该方法通过修改 HTTP 协议的 HEADER 部分,对浏览器下达重定向指令的,让浏览器对在 location 中指定的 URL 提出请求,使浏览器显示重定向网页的内容。该方法可以接受绝对的或相对的 URLs。如果传递到该方法的参数是一个相对的 URL,那么 Web container 在将它发送到客户端前会把它转换成一个绝对的 URL。

注释

123
// 第一种 请求转发response.setContentType("text/html; charset=UTF-8");response.sendRedirect("/Tomcat_Test/b");

运行 a.java 测试 “重定向”

3.JavaScript


另还有一种跳转页面的方法,也就是在 Servlet 中输出 JavaScript 代码,也能实现页面的跳转

PrintWriter out = request.getWriter();
out.println("<script>window.location.href = "url"</script>");
out.flush();
out.close();

这种方法和 response.sendRedirect () 的效率是差不多的,也要向服务器发出再次请求才能跳转到的 URL。

4. 小结


  • 0、跳转 (forward) 是在服务器端实现的,客户端浏览器并不知道该浏览动作,而使用 sendRedirect 跳转时,跳转是在客户端实现的,也就是说客户端浏览器实际上请求了 2 次服务器。
  • 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 不能这样处理相对路径。

Servlet 的三种跳转方式的更多相关文章

  1. java:struts框架2(方法的动态和静态调用,获取Servlet API三种方式(推荐IOC(控制反转)),拦截器,静态代理和动态代理(Spring AOP))

    1.方法的静态和动态调用: struts.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCT ...

  2. VMware的三种网络连接方式区别

    关于VMware的三种网络连接方式,NAT,Bridged,Host-Only ,在刚接触的时候通常会遇到主机Ping不通虚拟机而虚拟机能Ping得通主机:主机与虚拟机互不相通等等网络问题.本文就这三 ...

  3. .NET中的三种接口实现方式

    摘自:http://www.cnblogs.com/zhangronghua/archive/2009/11/25/1610713.html 一般来说.NET提供了三种不同的接口实现方式,分别为隐式接 ...

  4. Apache Spark探秘:三种分布式部署方式比较

    转自:链接地址: http://dongxicheng.org/framework-on-yarn/apache-spark-comparing-three-deploying-ways/     目 ...

  5. [转]详述DHCP服务器的三种IP分配方式

    DHCP就是动态主机配置协议(Dynamic Host Configuration Protocol),它的目的就是为了减轻TCP/IP网络的规划.管理和维护的负担,解决IP地址空间缺乏问题.这种网络 ...

  6. Binding 中 Elementname,Source,RelativeSource 三种绑定的方式

    在WPF应用的开发过程中Binding是一个非常重要的部分. 在实际开发过程中Binding的不同种写法达到的效果相同但事实是存在很大区别的. 这里将实际中碰到过的问题做下汇总记录和理解. 1. so ...

  7. windows phone 三种数据共享的方式(8)

    原文:windows phone 三种数据共享的方式(8) 本节实现的内容是数据共享,实现的效果描述:首先是建立两个页面,当页面MainPage通过事件导航到页面SecondPage是,我们需要将Ma ...

  8. 从壹开始前后端分离【 .NET Core2.0 +Vue2.0 】框架之十二 || 三种跨域方式比较,DTOs(数据传输对象)初探

    更新反馈 1.博友@落幕残情童鞋说到了,Nginx反向代理实现跨域,因为我目前还没有使用到,给忽略了,这次记录下,为下次补充.此坑已填 2.提示:跨域的姊妹篇——<三十三║ ⅖ 种方法实现完美跨 ...

  9. Kubernetes的三种外部访问方式:NodePort、LoadBalancer和Ingress(转发)

    原文 http://cloud.51cto.com/art/201804/570386.htm Kubernetes的三种外部访问方式:NodePort.LoadBalancer和Ingress 最近 ...

随机推荐

  1. 【OGG 故障处理】 丢失归档恢复

    OGG 有两天由于某种原因没有启动,而这段时间的备份文件缺失了一部分归档.恢复过程记录如下: GGSCI (xxxx) > info all Program Status Group Lag a ...

  2. JAVA Calendar类获取上个月的第一天和最后一天

    原文:https://www.cnblogs.com/QQParadise/articles/4936313.html 获取上个月第一天的方法: Calendar calendar = Calenda ...

  3. Codeforces 1187 F - Expected Square Beauty

    F - Expected Square Beauty 思路:https://codeforces.com/blog/entry/68111 代码: #pragma GCC optimize(2) #p ...

  4. 文件已经传输过来,数据在data,http接收

  5. P1396 营救[最短路+二分]

    题目描述 “咚咚咚……”“查水表!”原来是查水表来了,现在哪里找这么热心上门的查表员啊!小明感动的热泪盈眶,开起了门…… 妈妈下班回家,街坊邻居说小明被一群陌生人强行押上了警车!妈妈丰富的经验告诉她小 ...

  6. vue-cli webpack打包后index.html引入文件没有引号

    参考地址:https://blog.csdn.net/i_coffer/article/details/81005733 在对vue-cli项目打包后出现index.html引入的css和js没有引号 ...

  7. go语言信号量的使用例子

    //shared values are passed around on channels // 信号量. /* var sem = make(chan int, MaxOutstanding) fu ...

  8. js中in关键字的使用方法

    1.for...in 对数组或对象的循环/迭代操作 对于数组循环出来的是数组元素:对于对象循环出来的是对象属性 2.判断对象是否是数组/对象的元素/属性 格式:(变量 in 对象) 当‘对象’是数组时 ...

  9. Springboot AOP写操作日志 GET POST

    pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  10. 第六章 Flask数据库(一)之SQLAlchemy

    将ORM模型映射到数据库中 1. 用`declarative_base`根据`engine`创建一个ORM基类. from sqlalchemy.ext.declarative import decl ...