RequestDispatcher对象 请求转发
请求转发,地址不改变
context.getRequestDispatcher("/getInitParameter").forward(req,resp);
代码示例如下
import javax.servlet.RequestDispatcher;
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 ReqDispatcher extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
/*
RequestDispatcher requestDispatcher = context.getRequestDispatcher("/getInitParameter");
requestDispatcher.forward(req,resp);
*/
context.getRequestDispatcher("/getInitParameter").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
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"
metadata-complete="true">
<servlet>
<servlet-name>reqDispatcher</servlet-name>
<servlet-class>com.mahe666.servlet.ReqDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>reqDispatcher</servlet-name>
<url-pattern>/reqDispatcher</url-pattern>
</servlet-mapping>
</web-app>