O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

16.1. Setting ServletContext Attributes in Servlets

Problem

You want to make an object available to all servlets in a context or web application.

Solution

Bind an object to the ServletContext using the javax.servlet.ServletContext.setAttribute( ) method.

Discussion

A ServletContext attribute is available to all servlets and JSPs in a context or web application. Here are the steps to bind an object to a ServletContext:

  1. Create the Java class that you want to bind to a ServletContext.

  2. Place the class in the WEB-INF/classes directory, including the necessary package-related directories. You can also store the class in a JAR file in WEB-INF/lib.

  3. Create a servlet that binds the object to the ServletContext using the javax.servlet.ServletContext.setAttribute( ) method.

  4. Access the object using ServletContext.getAttribute( ) in (other) servlets whenever it is needed.

I'll first show the object that this recipe binds to the ServletContext. The recipe then demonstrates a servlet that stores the object attribute in the ServletContext. Example 16-1 shows a simple object wrapped around a java.util.Map type. Use the Map to store a characteristic of each request made to the web application. In this example, each Map key is the IP address of the client making the request. Each Map value is the date it requested the servlet.

Example 16-1. The object that a servlet binds to the ServletContext

package com.jspservletcookbook; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required