Servlet ServletContext

In this tutorial you will learn about the Servlet ServletContext and its application with practical example.

Servlet ServletContext Interface

At the time of deploying the project servlet container create ServletContext object. It defines a set of methods that a servlet uses to communicate with it’s servlet container. This object used to get configuration information from web.xml file, Remember one thing there is only one ServletContext object per web application. If any information is going to share into many servlet so its better to use <context-param> in the web.xml file. Like below code.

Usage :-

Table Of Contents

There are many important usage of ServletContext Interface. Here I have discussed some of them.

  • We can set,get and remove attributes from the web.xml file with the help of ServletContext Interface.
  • This object is used to get configuration information from the web.xml file.
  • This object is used to provides an interface between the servlet container and servlet.
  • It also provides inter-application communication.
  • it is available to all Servlets and JSPs files which are part of web app.

ServletContext Interface Methods

There are so many methods are in ServletContext Interface, some of them are listed below.

public String getInitParameter(String name):- This methods is used to returns the parameter value by the specified name.

public Enumeration getInitParameterNames() : This method is used to returns the an Enumeration which contains the names available within servlet context.

public void setAttribute(String name,Object object) :- This method is used to binds an object to a given attribute name in the servlet context.

public Object getAttribute(String name) :- This method returns the servlet container attribute with the given name, or if there is no attributes it returns null.

public void removeAttribute(String name) :- This method is used to remove the attribute with the given name from the servlet context.

ServletContext getServletContext() :- It returns a ServletContext object .

public String getServerInfo() :- This method returns the name and version of the servlet container.


Let’s understand this interface by an example. :-

In this servlet we get the data with the help of getServletContext() method (which returns the object of ServletContext interface) and the data is initialized in the web.xml file. Check below code:

Web.xml :-

follow the below code to set <context-param>.

Output :-

The output of this code will look like below image.



In this tutorial we have learn about the Servlet ServletContext and its application with practical example. I hope you will like this tutorial.