random thoughts

HOWTO Pass Request and Response From One Servlet to Another Servlet …

…that sounds simple for a java/j2ee programmer…

RequestDispatcher rd = request.getRequestDispatcher”/jsps/login.jsp”);
rd.forward(request,response);

but the scenario is …
i have to pass the request and response from a servlet in one web application to another servlet or jsp in another web application deployed in the same server …

lets say we have two web applications SabreNews and BeanPicks

and we have to pass the request and response object from a Servlet or a jsp in SabreNews to a resource(Servlet or a jsp) in BeanPicks

how should we go about ?

here is the solution :

ServletContext beanPicksContext = getServletContext().getContext(“/BeanPicks”);
beanPicksContext.getRequestDispatcher(“/beanPicks/jsps/displayBlog.jsp”).forwa rd(request,response);

getServletContext() is the method declared in the ServletConfig object .As the method name goes by , it returns the ServletContext object with which a Servlet can communicate with the ServletContainer in which the webapplication runs.
so now we have got the line to talk with the ServletContainer which also holds other web applications and BeanPicks too .

Now , we have to ask for the BeanPicks’s context and we get the BeanPicks context by calling getContext(“/BeanPicks”)

we have got the context and the rest is to get the RequestDispathcher(getRequestDispatcher(java.lang.String path)) on a particular resource (displayBlog.jsp) and forward the request and response

i am using the code snippet i have given above , in my web application and it is working fine for me .if there is another way doing it , please blog it and let me know.

please refer to J2EE 1.4 api docs for brief information about ServletConfig , ServletResponse and GenericServlet objects

Comments