tags:

views:

53

answers:

2

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

public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain) throws ServletException, IOException {
     HttpServletRequest aHttpServletRequest = (HttpServletRequest) request;
     aHttpServletRequest.getRequestDispatcher("/init.jsp").include(request, response);
     chain.doFilter(request, response);
}
A: 

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.

skaffman
+2  A: 

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.

ZZ Coder