[ Team LiB ] Previous Section Next Section

Recipe 16.3 Accessing or Removing ServletContext Attributes in Servlets


You want to access a ServletContext attribute to work with it in code, or completely remove it.


Use the ServletContext.getAttribute(String attributeName) method to access the attribute. Use the ServletContext.removeAttribute(String attributeName) method to remove the attribute from the ServletContext.


The code in Example 16-5 gets the ServletContext attribute and stores it in a local variable. Then the code adds a new key/value to the attribute (which contains a java.util.Map type for storing the keys and values). Later, the servlet prints out a list of the attribute's keys, which are IP addresses associated with requests to the servlet.

Example 16-5. Accessing a ServletContext attribute in a servlet
package com.jspservletcookbook;           

import javax.servlet.*;
import javax.servlet.http.*;

public class ContextAccessor extends HttpServlet {

  public void doGet(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException,
    java.io.IOException {
    //get a ServletContext attribute
    ContextObject contextObj = (ContextObject)
        getServletContext( ).getAttribute(
    if (contextObj != null)
        contextObj.put(request.getRemoteAddr( ),""+
            new java.util.Date( ));
    //display the context attribute values
      java.io.PrintWriter out = response.getWriter( );
          "<html><head><title>Context Attribute</title></head><body>");

      if (contextObj != null){
          out.println("<h2>ServletContext Attribute Values</h2>");
          out.println(contextObj.getValues( ));
      } else {
          out.println("<h2>ServletContext Attribute is Null</h2>");
  } //end doGet

Example 16-1 in Recipe 16.1 shows the ContextObject source code. Here, the ContextObject put( ) method passes its key and value parameters to the Map method of the same name, except that the ContextObject put( ) method does not allow null values for either its keys or values.

If you want to remove the same attribute that was bound by this recipe, call the ServletContext.removeAttribute( ) method with the attribute name as a parameter:

getServletContext( ).removeAttribute(

After the attribute removal code executes, any further calls to ServletContext.getAttribute( ) using the same attribute name will return null.

See Also

Recipe 16.1 and Recipe 16.2 on setting ServletContext attributes in servlets and JSPs; Recipe 16.5-Recipe 16.8 on handling session attributes in servlets and JSPs; Recipe 16.9-Recipe 16.12 on handling request attributes in servlets and JSPs; Recipe 14.5 on using a ServletContext event listener; the Javadoc for javax.servlet.ServletContextAttributeListener: http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ServletContextAttributeListener.html.

    [ Team LiB ] Previous Section Next Section