Servlet请求转发

请求转发(RequestDispatcher)

有时候 Tomcat 把请求发到某个 Servlet 时,如果不希望该 Servlet 进行处理,可以将其转发给其他 Servlet 处理。通过 ServletContext 获取 RequestDispatcher 对象并调用 forward 方法即可实现请求转发。

ServletContext context = this.getServletContext(); // 获取ServletContext对象
RequestDispatcher rd = context.getRequestDispatcher("/other"); // 获取请求转发对象(RequestDispatcher)
rd.forward(request, response); // 调用forward方法实现请求转发Code language: JavaScript (javascript)

以上代码在 HomeServlet 中执行,浏览器访问的是 HomeServlet,但实际由 /other 地址对应的 Servlet 处理,浏览器显示的却是 OtherServlet 的内容。对于客户端来说,用户感觉不到是 OtherServlet 处理的,地址栏仍然显示 /home

注意事项

如果在 Servlet 中重写了 init(ServletConfig config) 方法并自行维护了 ServletConfig 引用,则不能直接通过 this.getServletContext() 获取上下文对象,否则会获取不到。应当使用 this.config.getServletContext() 来获取:

public class HomeServlet extends HttpServlet implements SingleThreadModel {
    private static final long serialVersionUID = 1L;

    private int i;

    private ServletConfig config;

    public HomeServlet() {
    }

    public void init(ServletConfig config) throws ServletException {
        this.config = config;
    }

    public void destroy() {
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        super.service(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = this.config.getServletContext(); // 正确方式:通过config获取ServletContext
        RequestDispatcher rd = context.getRequestDispatcher("/other");
        rd.forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().write("doPost----");
    }
}Code language: PHP (php)

说明SingleThreadModel 接口已在 Servlet API 2.4 中被标记为过时,实际开发中不建议使用。上述代码仅为演示目的保留。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注