What is the difference between RequestDispatcher and NamedDispatcher?

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>Test</servlet-name>
<url-pattern>/tes</url-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.
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.

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>FirstServlet</servlet-name>
<servlet-class>com.example.ServletExample</servlet-class>
</servlet>

RequestDispatcher dispatch = request.getNamedDispatcher(?FirstServlet?);
dispatch.forward(request, response);

1 comment:

  1. good but what is The meaning of ? mark in request.getNamedDispatcher(?FirstServlet?);

    ReplyDelete