本文共 1453 字,大约阅读时间需要 4 分钟。
在getRequestDispatcher接口下有俩个方法,分别是forward和include
首先,看一下使用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/