可以使用ServletContext中的getRequestDispatcher(url).forward(request, response)方法进行转发
myservlet2.java
public class myservlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("我要办事");
System.out.println("你的事我办不了");
System.out.println("你的事我找人帮你办");
ServletContext application=this.getServletContext();
//将请求向下传递
application.getRequestDispatcher("/demo3").forward(request, response);
System.out.println("事办完了");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
} }
myservlet3.java
public class myservlet3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("这个事我能办");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
} }
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name> <servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>myservlet2</servlet-name>
<servlet-class>com.zk.myservlet.myservlet2</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>myservlet3</servlet-name>
<servlet-class>com.zk.myservlet.myservlet3</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>myservlet2</servlet-name>
<url-pattern>/demo2</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>myservlet3</servlet-name>
<url-pattern>/demo3</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
运行效果:此案例从myservlet2.java中间转发至myservlet3.java
程序结构