请求转发不会改变url地址,页面显示转发地址的内容。
首先,web.xml配置文件中有已经注册好的需要转发的Servlet,比如待转发servlet是该篇文章中的url-pattern为“/getjdbc“的servlet;
然后,获取ServletContext对象,并编辑转发代码;
package com.java.demo
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ServletResquestDispatcher extends HttpServlet{
protected void doGet(HttpServletResquest req,HttpServletResponse resp) throws ServletException, IOException{
//获取ServletContext对象
ServletContext context=this.getServletContext();
//使用请求转发方法,设置转发url,
context.getResquestDispatcher("/getjdbc").forward(req,resp);
}
}
最后,注册此servlet,并设置Tomcat,运行。
<servlet>
<servlet-name>getResquestDispatcher</servlet-name>
<servlet-class>com.java.demo.ServletResquestDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getResquestDispatcher</servlet-name>
<url-pattern>/getRD</url-pattern>
</servlet-mapping>