Difference between ServletConfig and ServletContext in Java Servlet

Difference between ServletConfig and ServletContext in Java Servlet is popular question in java interview. Let see following are differences.

No. of web applications = That many number of ServletContext objects

No. of servlet classes = That many number of ServletConfig objects.

Usage of ServletContext Interface

There can be a lot of usage of ServletContext object. Some of them are as follows:

  • The object of ServletContext provides an interface between the container and servlet.
  • The ServletContext object can be used to get configuration information from the web.xml file.
  • The ServletContext object can be used to set, get or remove attribute from the web.xml file.
  • The ServletContext object can be used to provide inter-application communication.
  • ServletContext object will be available even before giving the first request
  • In web.xml – <context-param> tag will be appear under <web-app> tag

Usage of ServletConfig Interface

  • ServletConfig is implemented by the servlet container to initialize a single servlet using init(). That is, you can pass initialization parameters to the servlet using the web.xml deployment descriptor. For understanding, this is similar to a constructor in a java class.
  • An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from web.xml file.
  • If the configuration information is modified from the web.xml file, we don’t need to change the servlet. So it is easier to manage the web application if any specific content is modified from time to time.
  • We should give request explicitly, in order to create ServletConfig object for the first time
  • In web.xml – <init-param> tag will be appear under <servlet-class> tag

Previous