getRequestDispatcher() and getNamedDispatcher of the ServletContext

What is the difference between the getRequestDispatcher(String) and getNamedDispatcher(String) methods in the ServletContext Class?

NamedDispatcher

Returns a RequestDispatcher object that acts as a wrapper for the named servlet.

getNamedDispatcher(String) method takes the name of the Servlet as parameter which is declared via Deployment descriptor.

Example: Deployment Descriptor


<servlet>
<servlet-name>FirstServletservlet-name>
<servlet-class>com.example.ServletExampleservlet-class>
servlet>

RequestDispatcher dispatch = request.getNamedDispatcher(?FirstServlet?);


dispatch.forward(request, response);

Note: A servlet instance can determine its name using servletConfig.getServletName(); This method returns the name of the class that implements the Servlet interface or extends the HttpServlet class.

RequestDispatcher

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.

 RequestDispatcher dispatch = request.getRequestDispatcher("/tes");

Here "/tes" represents the url-pattern element value of the servlet class.


<servlet-mapping>
<servlet-name>Testservlet-name>
<url-pattern>/tesurl-pattern>
servlet-mapping>

It represents the path of the servlet class. Since both the base as well as target servlet are in the same package structure by just specifying the url-pattern element value we will be able to access the target servlet.

We shouldn't specify the entire path like

 String str = "/WEB-INF/classes/com/example/posr/Test"

 RequestDispatcher dispatch = request.getRequestDispatcher(str);

To forward a request to a JSP page we use

 RequestDispatcher dispatch = request.getRequestDispatcher("/TestJspOne.jsp");
Here "/TestJspOne.jsp" the slash denotes the Jsp page is at the root of the application.

There is another way to get the request dispatcher object.

RequestDispatcher dispatch = request.getRequestDispatcher(arg);

where arg (a string) can be a relative path or not to a particular resource. (i.e. jsp, servlet, etc.) It may be both a relative (not starting with '/') or relative (to this request) URL.


The Main Difference is:
forwards and includes to servlet has access to 5 request attributes each.

javax.servlet.forward.request_uri
javax.servlet.forward.context_path
javax.servlet.forward.servlet_path
javax.servlet.forward.path_info
javax.servlet.forward.query_string

AND

javax.servlet.include.request_uri
javax.servlet.include.context_path
javax.servlet.include.servlet_path
javax.servlet.include.path_info
javax.servlet.include.query_string



And, all of these are not present when dispatched through getNamedDispatcher.

Comments