Friday, 22 April 2016

getNamedDispatcher() vs. getRequestDispatcher()


getNamedDispatcher(ServletName)
takes the Servlet name as parameter declared in web.xml and returns the RequestDispatcher.
<servlet>
    <servlet-name>FirstServlet</servlet-name>
    <servlet-class>com.genius.ServletExample</servlet-class>
</servlet>

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

Note : A servlet instance can determine its name using servletConfig.getServletName();
which returns the name of the class that implements or extend Servlet / HttpServlet.


getRequestDispatcher(URLPattern)
takes URL pattern of servlet and returns the RequestDispatcher.
<servlet-mapping>
    <servlet-name>Test</servlet-name>
    <url-pattern>/tes</url-pattern>
</servlet-mapping>

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

To forward a request to a JSP page we can use :
RequestDispatcher dispatch = request.getRequestDispatcher("/TestJspOne.jsp");
Here "/TestJspOne.jsp" will look the JSP page at the context root of the application.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.