开发者

RequestDispatcher in Java

What exactly the main purpose of using RequestDispatcher, for example when it's executed in Filter like the following example:

public void doFilter(ServletRequest reques开发者_JAVA技巧t, ServletResponse response,
    FilterChain chain) throws ServletException, IOException {
     HttpServletRequest aHttpServletRequest = (HttpServletRequest) request;
     aHttpServletRequest.getRequestDispatcher("/init.jsp").include(request, response);
     chain.doFilter(request, response);
}


In your case, the output of JSP is prepended to every page that filter is attached. This is a technique to easily add a common header to all your pages.

It's a little bit confusing when RequestDispatcher is used int his context. Normally, when you want to dispatch your request to another servlet or JSP for process, you use RequestDispatcher to forward to another resource. In this case, your request is not dispatched anywhere else, instead you include output generated by another resource to your current response.


The javadoc says is better than I can:

RequestDispatcher:

Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.

In other words, you obtain a RequestDispstcher when you want to include from, or forward to, another resource on the server.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜