为了实现代码重用,需要将某些代码和数据放在一个或多个Servlet中,以供其他Servlet使用,提供了RequestDispatcher.include方法,首先通过getServletContext方法获取ServletContext对象,然后通过ServletContext.getRequestDispatcher方法获取RequestDispatcher对象。
以下代码中,IncludingServlet类演示了如何使用Include方法包含web资源。
//包含了一个Servlet:IncludedServlet,和一个HTML页面
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
// 设置Context-type字段值,类型为text/html,编码格式为utf-8
// response.setHeader("Content-type", "text/html;charset:utf-8");
response.setContentType("text/html;charset=utf-8");
// 获取PrintWriter对象
PrintWriter out = response.getWriter();
// response.setCharacterEncoding("UTF-8");
// 向客户端输出信息
out.println("hello world<br/>");
// 向客户端输出请求URI
out.println("Including URI:" + request.getRequestURI() + "<p/>");
// 封装名为IncludedServlet的Servlet
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/IncludedServlet");
rd.include(request, response);
// 封装名为IncludedHTML.html页面
rd = getServletContext().getRequestDispatcher("/IncludedHTML.html");
rd.include(request, response);
}
1.里面包含两个web资源,映射路径为“/IncludedServlet”的Servlet类和一个名为IncludedHTML.html的静态页面
2.getRequestDispatcher方法的参数值必须以“/”开头。
IncludedServlet类的代码
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//设置Context-type字段值,类型为text/html,编码格式为UTF-8
response.setContentType("text/html;charset=UTF-8");
//获取PrintWriter对象
PrintWriter out=response.getWriter();
//向客户端输出带HTML代码的信息
out.println("<b>crazy</b><br/>");
//向客户端输出请求URI
out.println("IncludedServlet URI:"+request.getRequestURI()+"<p/>");
}
IncludedHTML.html的代码
<!-- 利用表格显示相关信息 -->
<table border="1">
<tr>
<td>name</td>
<td>sex</td>
</tr>
<tr>
<td>zhang</td>
<td>male</td>
</tr>
<tr>
<td>zheng</td>
<td>female</td>
</tr>
</table>
运行结果如图