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.11. Accessing or Removing Request Attributes in Servlets

Problem

You want a servlet to access or remove a request attribute.

Solution

Use the javax.servlet.ServletRequest.getAttribute( ) and javax.servlet.ServletRequest.removeAttribute( ) methods, including the name of the attribute as the method parameter.

Discussion

Example 16-13 is derived from the doGet( ) method of Example 16-11 in Recipe 16.9 (refer to that class if you need to review the complete code of a servlet handling request attributes). Example 16-13 gets an object attribute from the HttpServletRequest object, which is the doGet( ) method's first parameter.

Tip

The servlet container creates an HttpServletRequest object and passes it as the first parameter to all of the HttpServlet's service methods, including doGet( ) and doPost( ).

Example 16-13 calls one of the attribute's methods, then removes the request attribute.

Example 16-13. A servlet accesses and removes a request attribute

public void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, java.io.IOException {ContextObject obj = (ContextObject) request.getAttribute(
        "com.jspservletcookbook.ContextObject");

    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter( );
    out.println(
        "<html><head><title>Request Attribute</title></head><body>");

    //display the attribute's Map keys
    out.println("<h2>Request attribute values</h2>");

    if (obj != null) out.println( obj.getValues( ) ); //This method call may not be ...

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