[ Team LiB ] |
![]() ![]() |
Recipe 16.11 Accessing or Removing Request Attributes in ServletsProblemYou want a servlet to access or remove a request attribute. SolutionUse the javax.servlet.ServletRequest.getAttribute( ) and javax.servlet.ServletRequest.removeAttribute( ) methods, including the name of the attribute as the method parameter. DiscussionExample 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.
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 attributepublic 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 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 AlsoRecipe 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: http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ServletRequestAttributeListener.html. |
[ Team LiB ] |
![]() ![]() |