Recipe 16.11 Accessing or Removing Request Attributes in Servlets


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


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


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.

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, {  ContextObject obj = (ContextObject) request.getAttribute(         "com.jspservletcookbook.ContextObject");  response.setContentType("text/html"); 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 necessary as request attributes     //persist only as long as the request is being handled,      //according to the ServletRequest API documentation.      request.removeAttribute("com.jspservletcookbook.ContextObject");  out.println("</body></html>");        } //doGet 

If the attribute does not exist in the request (because it was not bound to the request in the first place), ServletRequest.getAttribute( ) returns null . Make sure the servlet code checks for a null value before it calls the object's methods. In addition, the ServletRequest.getAttribute( ) method returns an Object type, so ensure that the servlet code casts the return value to the proper type before calling the expected type's methods.

See Also

Recipe 16.1-Recipe 16.4 on handling ServletContext attributes in servlets and JSPs; Recipe 16.5-Recipe 16.8 on handling session attributes in servlets and JSPs; Recipe 16.12 on accessing or removing request attributes in JSPs; Chapter 6 on including content in servlets and JSPs; the Javadoc for javax.servlet. ServletRequestAttributeListener :

Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: