Monday, March 29, 2010

Use of getServletContext()

When i was doing a project there was a necessity to send an object from one servlet to another servlet. Actually, i was implementing MVC architecture so you can understand in between servlets there is a JSP. So, here is the problem. How to forward an object between servlets?

I came up with an idea of putting the object into session. But, my brother told session is not at all a good idea because it takes lot of server resource. Later, I came up with an idea of using request object and faced trouble sending the objects in request object.

I was thing to implement the logic in different way so that i do not need to send the object to other servlet and i did it with the help of javascript.

Even after the completion of the project, i have question in my mind Is there any other way to send an object between servlets? i found the answer, that is getServletContext()

In servlet1
Resident r=new Resident();
...
...
getServletContext().setAttribute("Obj",r);

In servlet2

Object o= getServletContext().getAttribute("Obj");
Resident r=(Resident)o;


Example:

 




Corrections:
The way i implemented above is wrong for forwarding an Object to another Servlet, the correct way is to put it in Session scope or request scope and then access it. ServletContext is more like static or global declaration for all Servlet's.