ServletContext Interface in Servlet

As of now, We have discussed the ServletConfig Interface. In this article, we will discuss the ServletContext Interface. As we know, the ServletConfig object is created for every application. Unlike this, ServletContext is created only once per application.

What is ServletContext Interface?

ServletContext defines a certain method that a servlet uses to communicate with the web container. The object of ServletContext can be used to get the configuration information from the web.xml.When we deploy the project the object of ServletContext is created.

This is how we create the ServletContext Object.

ServletContext sc=getServletContext();

Advantages of ServletContext

  • If any information is changed in web.xml then the changes will be available to all the servlet.
  • It can be used to get configuration information from web.xml.
  • It can be used to get, set attribute.
  • In order to communicate between web containers and servlet ServletContext is used.

Methods in ServletContext Interface

  • public String getInitParameter(String name): This method is used to return the parameter value from the parameter name.
    • Parameter
      • name: It is a string that specified the name of the initialization parameter.
  • public Enumeration getInitParameterNames():This method returns the names of  context initialization parameter.
  • public void setAttribute(String name, String object): This method sets the attribute value for the given name.
    • Parameter
      • name: a string that specifies the name of an attribute.
      • object: an object of an attribute.
  • public Object getAtrribute(String name): This method returns the attribute of the specified name.
  • public String getServerInfo(): This method returns the server information on which servlet is running.
  • public String getContextPath(): This method returns the context path of the web application.

Let’s see the Example for ServletContext Interface

In this example, we have created ServletContextDemo.java servlet and called the method of ServletContext.Here, in place of the init parameter, we have to use the Context Initialization parameter in the web.xml file that will be accessible by every servlet in the web application.

Web.xml 

Output

 

ServletConfig

ServletContext

It is created one per servlet class. It is common to all servlets in web applications.
It will be created during initialization. It will be created at the time of deployment.
It will be destroyed once the servlet execution is completed It will be destroyed once the application is removed from the server.
<init-param> tag is used here <context-param> tag is used here
We should give requests explicitly for the first time. ServletContext object will be available before the first request.
getServletConfig() is used here. getServletContext() is used here.