ServletConfig interface is specific to a particular Servlet. It cannot read other Servlet <init-param> data because <init-param> is written within <servlet> tag.
What is ServletContext?
On the contrary, ServletContext is global. The ServletContext object can be used by all the Servlets under execution in an application. Application comprises of many programs bundled together to achieve a task. One Servlet can place the data with the ServletContext object and another can make use of the data. Otherway, it can be said, ServletContext is used for inter-servlet communication.
Some points to know about ServletContext interface.
- ServletContext is an interface from javax.servlet package and its object can be obtained with getServletContext() method of ServletConfig.
- That is, if a Servlet would like to create an object of ServletContext, it must come through ServletConfig object only as follows.
ServletConfig config1 = getServletConfig();
ServletContext context1 = config1.getServletContext();
- A ServletContext object being global, any servlet can access the data or modify the data or place the data.
- The ServletContext object comes into existence when the container starts and destroyed when the container stops execution.
- The ServletContext object is used to communicate between all servlets (inter-servlet communication)
- Data can be placed with the ServletContext object with "void setAttribute(String, Object)" method and can be retrieved later with "Object getAttribute(String)" method defined in ServletContext itself.
A full program with explanation and screenshot is given in Reading Servlets Context Parameter with Example.
Pass your comments and suggestions on this tutorial What is ServletContext?.