RequestDispatcher

The RequestDispatcher class enables your servlet to “call” another servlet from inside another servlet. The other servlet is called as if an HTTP request was sent to it by a browser.

You can obtain a RequestDispatcher from the HttpServletRequest object, like this:

protected void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws ServletException, IOException {

  RequestDispatcher requestDispatcher =
    request.getRequestDispatcher("/anotherURL.simple");
}

The above code obtains a RequestDispatcher targeted at whatever Servlet (or JSP) that is mapped to the URL /anotherUrl.simple.

You can call the RequestDispatcher using either its include() or forward() method:

requestDispatcher.forward(request, response);

requestDispatcher.include(request, response);

By calling either the include() or forward() method the servlet container activates whatever Servlet is mapped to the URL the RequestDispatcher.

The activated servlet has access to the same request as the servlet calling it, and will write to the same response as your current servlet. That way you can merge the output of servlets into a single repsonse.

There is a little difference between calling the forward() and include() method.

The forward() method intended for use in forwarding the request, meaning after the response of the calling servlet has been committed. You cannot merge response output using this method.

The include() method merges the response written by the calling servlet, and the activated servlet. This way you can achieve “server side includes” using the include().

Personally, I mostly use the include() method.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值