ServletContext Interface

Servlet ServletContext is an interface which belongs to javax.servlet package.

Only one ServletConfig Object gets created per application or web container.

The ServletConfig used to get an information from web.xml using <context-param> tag and it is common for all Servlets.

Changes made in web.xml file will not require any change in the servlet class.

ServletContext is all about reading configuration from web.xml file. It also created a relation in between container and Servlet.

There are two ways to create ServletContext object:

ServletContext servletContext = getServletContext();

ServletContext servletContext = getServletConfig().getServletContext();

ServletConfig uses <content-param> tag to set an data on initial load for servlet with the help of <param-name> and <param-value>

Below are the methods defined as part of ServletContext interface:

getInitParameter(String key)): This will return parameter value from <param-value> tag depending upon parameter name (<param-name> tag) .

getInitParameterNames(); This will return all parameter name written inside <param-param> tag.

public void setAttribute(String name,Object object): This method sets an Object in application scope.

Object getAttribute(String name): This method return Object from application scope.

public void removeAttribute(String name):This method remove Object from application scope.

Example

Create a LoginServlet.java class with the below content mentioned in below screenshot:

Create a web.xml file with the below content to provide data related to the LoginServlet.java servlet class.

OUTPUT

Country = India
param = country
Attribute before remove = test
Attribute after remove = null

Note: As mentioned earlier, ServletContext object share by all Servlets. Setting an attribute as part of ServletContext by one of the Servlet can be access by all other Servlet in the same web container.

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan