原文地址: RequestDispatcher接口include方法
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>IncludedServlet</servlet-name>
<servlet-class>com.RequestDispatcher.IncludedServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>IncludedServlet</servlet-name>
<url-pattern>/IncludedServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>IncludingServlet</servlet-name>
<servlet-class>com.RequestDispatcher.IncludingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>IncludingServlet</servlet-name>
<url-pattern>/IncludingServlet</url-pattern>
</servlet-mapping>
</web-app>
IncludingServlet.java:
public class IncludingServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
RequestDispatcher dispatcher=request.getRequestDispatcher("/IncludedServlet?pl=abc");
out.println("before including"+"<br>");
dispatcher.include(request,response);
out.println("after including");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
this.doGet(request,response);
}
}
IncludedServlet.java:
public class IncludedServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
out.println("中国"+"<br>");
out.println("URI:"+request.getRequestURI()+"<br>");
out.println("QueryString:"+request.getQueryString()+"<br>");
out.println("parameter pl"+request.getParameter("pl")+"<br>");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
this.doGet(request,response);
}
}