What is ServletContext interface?

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.

  1. ServletContext is an interface from javax.servlet package and its object can be obtained with getServletContext() method of ServletConfig.
  2. 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();
  3. A ServletContext object being global, any servlet can access the data or modify the data or place the data.
  4. The ServletContext object comes into existence when the container starts and destroyed when the container stops execution.
  5. The ServletContext object is used to communicate between all servlets (inter-servlet communication)
  6. 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?.

Leave a Comment

Your email address will not be published.