博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Servlet的请求转发getRequestDispatcher接口
阅读量:3959 次
发布时间:2019-05-24

本文共 1453 字,大约阅读时间需要 4 分钟。

getRequestDispatcher接口下有俩个方法,分别是forward和include

  • forward :使用该方法请求转发后,后续响应输出的代码不在执行,页面的输出只会输出最后一个转的页面的h5代码输出
  • include :使用该方法请求转发后,后续响应输出的代码不在执行,页面的输出会输出所有页面的h5代码

首先,看一下使用forward方法请求转发的实例;(仅给出doget里面的代码)

//设置编码格式,防止代码出现乱码的情况	request.setCharacterEncoding("utf-8");	response.setContentType("text/html;charset=utf-8");	PrintWriter out= response.getWriter();	//写入h5代码	out.print("hello demo ");	//请求转发后,跳转到test页面(下一个servlet),使用forward方法	request.getRequestDispatcher("test").forward(request, response);	out.print("000000000000000000");	out.close();	//控制台输出,俩种方法皆会输出该语句的结果	System.out.println("hello demo changsha");

下一个test的servlet页面一样,代码如下

request.setCharacterEncoding("utf-8");	response.setContentType("text/html;charset=utf-8");	PrintWriter out= response.getWriter();	out.print("hello test ");	out.print("111111111111111111111111");	out.close();	System.out.println("hello demo guangzhou");

看到控制台的输出,俩个界面的控制台输出语句均有输出

但是,在网页上的输出仅仅只有test页面的hello test 和后面的111111111输出


在者我们看一下使用include方法跳转页面的输出(include的代码与forward一致,方法不同),这个servlet的名字为Demo1,与前面一样,跳转到test页面,代码如下:

request.setCharacterEncoding("utf-8");	response.setContentType("text/html;charset=utf-8");	PrintWriter out= response.getWriter();	out.print("hello demo1 ");	request.getRequestDispatcher("test").include(request, response);	out.print("22222222222222222222222");	out.close();	System.out.println("hello demo zhongshan");

运行这个代码,跳转到test页面后看到控制台的输出一样,均已执行

在网页上的输出则是将Demo1和test的h5代码合并在一起,表示该方法会将所有界面的h5代码执行并输出

转载地址:http://cxmzi.baihongyu.com/

你可能感兴趣的文章