java2db

How to create RequestDispatcher object ( servlet chaining )



The RequestDispatcher object is useful to communicate one servle/JSP with another servlet/JSP.

It is the object of servlet container supplied java class that implements javax.servlet.RequestDispatcher interface.

create RequestDispatcher object Creating RequestDispatcher object with  ServletRequest object :

Example:
public void doGet(HttpServletRequest request, HttpServletResponse response) {
try
{
RequestDispatcher dispatcher = request.getRequestDispatcher(“/test“);
————————————-
————————————-
}
catch(Exception exception)
{
exception.printStackTrace();
}
}

 

It is suitable , if  both the source and destination servlets are reside in the same web application.

It takes the String (url pattern) as an argument .

 

 

create RequestDispatcher object Creating RequestDispatcher object with ServletContext object :

Example:

public  void doGet(HttpServletRequest request, HttpServletResponse response) {
try
{
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher(“/test“);
————————————-
————————————-
}
catch(Exception exception)
{
exception.printStackTrace();
}
}

It takes the String (url pattern) of the destination servlet or jsp/html file name as an argument.

It is suitable , if both source and destination servlets that reside in the same or different web applications in the same server.

 

create RequestDispatcher object Creating RequestDispatcher object with ServletContext object :

Example:

public  void doGet(HttpServletRequest request, HttpServletResponse response) {
try
{
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context .getNamedDispatcher(“ServletApp“);
————————————-
————————————-
}
catch(Exception exception)
{
exception.printStackTrace();
}
}

 

With this ,we cannot call any file (example : HTML file) other than the jsp or servlet.

It will take the String (servlet name/logical name) as an argument.

 

create a servletRequestDispatcher dispatches the request using  forward(-,-) , include(-,-)  methods.



Related Posts :
Kill or invalidate session using session id ( concurrent login )
Servlet Filter ( Request and Response filters in servlets ) example
URL rewriting in servlets ( Servlet session tracking )
Servlet Cookies ( Servlets session tracking with cookie )
Hidden form field in servlets ( Servlet session tracking )
Request attributes in servlet with an example ( Attribute scope )
Session attributes in servlet with example (Attribute scope)
ServletConext Attributes in servlet ( Attribute scope )
   [will not be published]



^ <