How servlet/jsp communicate with each other and with container using ServletContext?

A ServletContext is common for all servlets and jsps ain a webapp. They can communicate with each other and with container through that object.

The important methods of ServletContext:
The get/set Attribute is used for communication.
Suppose one servlet wants to share two objects(obj1,obj2) for all the web application. So it will do like this,
getServletContext.setAttribute(“first”,obj1);//the name “first” will be used for getting obj1
The servlets wants to get those objets will get like this,
now the servlet gets the object.
In JSP thing is little bit different. JSP has implicit object ServletContext. With that object we can get the objects.
getAttributeNames() returns an Enumeration holding all the data of ServletContext.
removeAttribute(String name) is to remove an attribute.

No comments:

Post a Comment