![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e1038. Saving Data in a ServletThere are three places a servlet can save data for its processing - in the request, in the session (if present), and in the servlet context (which is shared by all servlets and JSP pages in the context). Data saved in the request is destroyed when the request is completed. Data saved in the session is destroyed when the session is destroyed. Data saved in the servlet context is destroyed when the servlet context is destroyed.Data is saved using a mechanism called attributes. An attribute is a key/value pair where the key is a string and the value is any object. It is recommended that the key use the reverse domain name convention (e.g., prefixed with com.mycompany) to minimize unexpected collisions when integrating with third party modules. Note: The three locations are identical to the three scopes -- request, session, and application - - on a JSP page (see e1048 Saving Data in a JSP Page). So, if a servlet saves data in the request, the data will be available on a JSP page in the request scope. A JSP page-scoped value is simply implemented by a local variable in a servlet. This example saves and retrieves data in each of the three places: // Save and get a request-scoped value req.setAttribute("com.mycompany.req-param", "req-value"); Object value = req.getAttribute("com.mycompany.req-param"); // Save and get a session-scoped value HttpSession session = req.getSession(false); if (session != null) { session.setAttribute("com.mycompany.session-param", "session-value"); value = session.getAttribute("com.mycompany.session-param"); } // Save and get an application-scoped value getServletContext().setAttribute("com.mycompany.app-param", "app-value"); value = getServletContext().getAttribute("com.mycompany.app-param");The following example retrieves all attributes in a scope: // Get all request-scoped attributes java.util.Enumeration enum = req.getAttributeNames(); for (; enum.hasMoreElements(); ) { // Get the name of the attribute String name = (String)enum.nextElement(); // Get the value of the attribute Object value = req.getAttribute(name); } // Get all session-scoped attributes HttpSession session = req.getSession(false); if (session != null) { enum = session.getAttributeNames(); for (; enum.hasMoreElements(); ) { // Get the name of the attribute String name = (String)enum.nextElement(); // Get the value of the attribute Object value = session.getAttribute(name); } } // Get all application-scoped attributes enum = getServletContext().getAttributeNames(); for (; enum.hasMoreElements(); ) { // Get the name of the attribute String name = (String)enum.nextElement(); // Get the value of the attribute Object value = getServletContext().getAttribute(name); }
e1036. Getting and Setting Initialization Parameters for a Servlet e1037. Returning an Image in a Servlet e1039. Logging a Message in a Servlet © 2002 Addison-Wesley. |