Servlet转发

Posted longlyseul

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Servlet转发相关的知识,希望对你有一定的参考价值。

可以使用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

技术分享图片

程序结构

技术分享图片

 

 

 

以上是关于Servlet转发的主要内容,如果未能解决你的问题,请参考以下文章

Servlet笔记9--转发与重定向

Servlet中的转发与重定向的区别

Servlet中的转发与重定向的区别

Servlet RequestDispatcher 未转发

jsp页面转发到servlet

为啥 HttpServletRequest 对象在从一个 servlet 转发到另一个 servlet 时会发生变化?