Categories: Servlet

ServletContext Interface

An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application.If any information is shared to many servlet, it is better to provide it from the web.xml file using the element.

Advantage of ServletContext

Easy to maintain if any information is shared to all the servlet, it is better to make it available for all the servlet. We provide this information from the web.xml file, so if the information is changed, we don’t need to modify the servlet. Thus it removes maintenance problem.

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.
Methods Description
Object getAttribute(String name) returns the container attribute with the given name, or null if there is no attribute by that name.
String getInitParameter(String name) returns parameter value for the specified parameter name, or null if the parameter does not exist
Enumeration getInitParameterNames() returns the names of the context’s initialization parameters as an Enumeration of String objects
void setAttribute(String name,Object obj) set an object with the given attribute name in the application scope
void removeAttribute(String name) removes the attribute with the specified name from the application context

How to get the object of ServletContext

ServletContext app = getServletContext();
ServletContext app = getServletConfig().getServletContext(); 

 

How to get the object of ServletContext interface

getServletContext() method of ServletConfig interface returns the object of ServletContext.
    getServletContext() method of GenericServlet class returns the object of ServletContext.

Syntax of getServletContext() method

public ServletContext getServletContext()  

Example of getServletContext() method

//We can get the ServletContext object from ServletConfig object  
    ServletContext application=getServletConfig().getServletContext();  
      
    //Another convenient way to get the ServletContext object  
    ServletContext application=getServletContext();  

Example of ServletContext to get the initialization parameter

In this example, we are getting the initialization parameter from the web.xml file and printing the value of the initialization parameter. Notice that the object of ServletContext represents the application scope. So if we change the value of the parameter from the web.xml file, all the servlet classes will get the changed value. So we don’t need to modify the servlet. So it is better to have the common information for most of the servlets in the web.xml file by context-param element. Let’s see the simple example:
HelloServlet.java

import java.io.*;  
    import javax.servlet.*;  
    import javax.servlet.http.*;  
      
      
    public class HelloServlet extends HttpServlet{  
    public void doGet(HttpServletRequest req,HttpServletResponse res)  
    throws ServletException,IOException  
    {  
    res.setContentType("text/html");  
    PrintWriter pw=res.getWriter();  
      
    //creating ServletContext object  
    ServletContext context=getServletContext();  
      
    //Getting the value of the initialization parameter and printing it  
    String driverName=context.getInitParameter("driverName");  
    pw.println("driver name is="+driverName);  
      
    pw.close();  
      
    }
}  

web.xml

<web-app>  
      
    <servlet>  
    <servlet-name>HelloServlet</servlet-name>  
    <servlet-class>HelloServlet</servlet-class>  
    </servlet>  
      
    <context-param>  
    <param-name>driverName</param-name>  
    <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
    </context-param>  
      
    <servlet-mapping>  
    <servlet-name>HelloServlet</servlet-name>  
    <url-pattern>/context</url-pattern>  
    </servlet-mapping>  
      
    </web-app> 

Example of ServletContext to get all the initialization parameters

In this example, we are getting all the initialization parameter from the web.xml file. For getting all the parameters, we have used the getInitParameterNames() method in the servlet class.

HelloServlet.java

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
  
public class DemoServlet extends HttpServlet{  
public void doGet(HttpServletRequest req,HttpServletResponse res)  
throws ServletException,IOException  
{  
res.setContentType("text/html");  
PrintWriter out=res.getWriter();  
  
ServletContext context=getServletContext();  
Enumeration<string> e=context.getInitParameterNames();  
      
String str="";  
while(e.hasMoreElements()){  
    str=e.nextElement();  
    out.print("<br> "+context.getInitParameter(str));  
}  
}
}  

web.xml

<web-app>  
      
    <servlet>  
    <servlet-name>HelloServlet</servlet-name>  
    <servlet-class>HelloServlet</servlet-class>  
    </servlet>  
      
    <context-param>  
    <param-name>driverName</param-name>  
    <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
    </context-param>  
      
    <context-param>  
    <param-name>name</param-name>  
    <param-value>dinesh</param-value>  
    </context-param>  
      
    <context-param>  
    <param-name>email</param-name>  
    <param-value>admin@dineshonjava.com</param-value>  
    </context-param>  
      
    <servlet-mapping>  
    <servlet-name>HelloServlet</servlet-name>  
    <url-pattern>/context</url-pattern>  
    </servlet-mapping>  
      
    </web-app>  

 

 

 

<<Previous <<   || Index ||   >>Next >>

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago