Understanding ServletContext in Java Web Applications

1.3 ServletContext

ServletContext represents one of the three main scope objects available in Java web applications.

The ServletContext is instantiated when the server starts and destroyed when the server shuts down. Each Java web application contains exactly one ServletContext instance throughout its lifecycle.

1.3.1 ServletContext Overview

The server creates a unique ServletContext instance for each web application:

  • The ServletContext object is created during server startup;
  • The ServletContext object is destroyed during server shutdown.

The primary purpose of the ServletContext is to enable data sharing across all dynamic resources within a web application. For example, data stored in the ServletContext by one servlet can be accessed by another servlet, facilitating data exchange between different components.

Direct method calls between servlets should be avoided as it creates tight coupling.

1.3.2 ServletContext Functionalities:

  • Data storage and retrieval
  • Reading application initialization parameters from web.xml
  • Accessing application resources

1.3.3 Obtaining the ServletContext Object

In HttpServlet, the following methods can be used to obtain a ServletContext instance:

  • ServletContext context = this.getServletContext()
  • ServletContext context = this.getServletConfig().getServletContext()
  • servletConfig.getServletContext() also works
  • HttpSession can be used to access it
  • ServletContextEvent provides access

In the void init(ServletConfig config) method:

ServletContext context = config.getServletContext();

The getServletContext() method in the ServletConfig class can be used to retrieve the ServletContext object;

In GenericServlet or HttpServlet, getting the ServletContext is simpler:

The GenericServlet class provides a getServletContext() method, allowing direct access via this.getServletContext();

1.3.4 Data Storage and Retrieval

Since each Java web application has only one ServletContext instance, data stored in it can be shared across all dynamic resources in the application.

ServletContext is one of the three main scope objects in servlets, containing an internal Map for data storage.

Scope Object Functionality(Used for passing data between multiple servlets)

ServletContext is one of the four major scope objects in Java web applications:

  • PageContext;
  • ServletRequest;
  • HttpSession;
  • ServletContext;

1. Storing Data

  • void setAttribute(String name, Object value): Used to add or replace data in the ServletContext scope
servletContext.setAttribute("dataKey", "dataValue"); // Add scope data
servletContext.setAttribute("dataKey", "newValue"); // Replace existing data

2. Retrieving Data

  • Object getAttribute(String name): Retrieves scope data by name
  • void removeAttribute(String name): Removes scope data by name
  • Enumeration getAttributeNames(): Retrieves all names of stored data in the ServletContext scope

1.3.5 Reading Application Initializasion Parameters from web.xml

Servlets can have their own initialization parameters, but these are local to each servlet. A servlet can only access its own parameters, not those of other servlets.

You can configure global initialization parameters for all servlets using the ServletContext:

<context-param>
  <param-name>globalParam1</param-name>
  <param-value>value1</param-value>
</context-param>

<context-param>
  <param-name>globalParam2</param-name>
  <param-value>value2</param-value>
</context-param>

  • servletContext.getInitParameter("globalParam1") returns value1
  • servletContext.getInitParameter("globalParam2") returns value2
  • servletContext.getInitParameterNames() returns an Enumeration containing globalParam1 and globalParam2

1.3.6 Accessing Application Resources

To dynamically access resource paths:

  • String getRealPath(String path): Retrieves the real path of a resource
String realPath = servletContext.getRealPath("/WEB-INF/resource.jpg");

Returns the actual path of the resource, such as C:/tomcat/webapps/yourapp/WEB-INF/resource.jpg

Other resource access methods:

  • InputStream getResourceAsStream(String path): Gets an input stream for a resource
InputStream resourceStream = servletContext.getResourceAsStream("/WEB-INF/resource.jpg");

Returns an input stream object for the resource, allowing access to its content

  • Set getResourcePaths(String path): Retrieves all resource paths under a specified directory
Set<String> resourcePaths = servletContext.getResourcePaths("/WEB-INF");

Returns a Set containing strings like:

  • /WEB-INF/lib/*
  • /WEB-INF/classes/*
  • /WEB-INF/web.xml
  • /WEB-INF/resource.jpg

1.3.7 Accessing Classpath Resources

You can access resources in the classpath using Class objects. In Java web applications, the classpath corresponds to resources in the classes directory.

Example:

InputStream in = com.example.web.MyServlet.class.getResourceAsStream("resource.jpg");

Retrieves /WEB-INF/classes/com/example/web/resource.jpg, a resource in the same directory as MyServlet.class

Example with absolute path:

InputStream in = com.example.web.MyServlet.class.getResourceAsStream("/resource.jpg");

Retrieves /WEB-INF/classes/resource.jpg, a resource at the root of the classpath

IOUtils can be used to convert input streams to strings

Practice Exercise: Website Visit Counter

Create a counter that increments for every resource access in the appplication!

Create an integer variable to store the visit count and save it in the ServletContext scope, making it accessible to all servlets.

Initially, the ServletContext contains no visit count data;

When the site is first accessed, create a variable with value 1 and store it in the ServletContext;

For subsequent accesses, retrieve the variable from the ServletContext and increment it by 1.

Obtain the ServletContext object and check if a count attribute exists. If it doesn't exist, this is the first visit;

First visit: Use setAttribute() to store a count attribute with value 1;

Subsequent visits: Use getAttribute() to retrieve the current count, increment it by 1, and use setAttribute() to update the value.

1.3.8 Parameters vs. Attributes

Differences:

  • **Origin:**Parmaeters come from the client (browser) and are provided by users. For GET requests, they come from the URL; for POST requests, they come from the request body. Attributes are set by server-side components (JSP or Servlet) using request.setAttribute().
  • **Operations:**Parameter values can only be read, not modified, using request.getParameter(). Attribute values can both be read and modified using request.getAttribute() and request.setAttribute().
  • **Data Types:**Parameters are always treated as String types on the server, regardless of their semantic meaning. Client parameters can only be simple types, not complex objects. Attributes can be of any Object type.

Common Point: Both values are encapsulated within the request object.

Tags: Java Servlet API Web Application ServletContext Java EE Servlet Lifecycle

Posted on Tue, 28 Jul 2026 17:12:56 +0000 by teynon