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.3. Accessing or Removing ServletContext Attributes in Servlets

Problem

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

Solution

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.

Discussion

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(
        "com.jspservletcookbook.ContextObject");
        
    if (contextObj != null)
        contextObj.put(request.getRemoteAddr( ),""+
            new java.util.Date( )); //display the context attribute values response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter( ); out.println( "<html><head><title>Context Attribute</title></head><body>"); if ...

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