![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e1048. Saving Data in a JSP PageWhen a JSP page needs to save data for its processing, it must specify a location, called the scope. There are four scopes available - page, request, session, and application. Page - scoped data is accessible only within the JSP page and is destroyed when the page has finished generating its output for the request. Request-scoped data is associated with the request and destroyed when the request is completed. Session-scoped data is associated with a session and destroyed when the session is destroyed. Application-scoped data is associated with the web application and destroyed when the web application is destroyed. Application-scoped data is not accessible to other web applications.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. This example uses attributes to save and retrieve data in each of the four scopes: <% // Check if attribute has been set Object o = pageContext.getAttribute("com.mycompany.name1", PageContext.PAGE_SCOPE); if (o == null) { // The attribute com.mycompany.name1 may not have a value or may have the value null } // Save data pageContext.setAttribute("com.mycompany.name1", "value0"); // PAGE_SCOPE is the default pageContext.setAttribute("com.mycompany.name1", "value1", PageContext.PAGE_SCOPE); pageContext.setAttribute("com.mycompany.name2", "value2", PageContext.REQUEST_SCOPE); pageContext.setAttribute("com.mycompany.name3", "value3", PageContext.SESSION_SCOPE); pageContext.setAttribute("com.mycompany.name4", "value4", PageContext.APPLICATION_SCOPE); %> <%-- Show the values --%> <%= pageContext.getAttribute("com.mycompany.name1") %> <%-- PAGE_SCOPE --%> <%= pageContext.getAttribute("com.mycompany.name1", PageContext.PAGE_SCOPE) %> <%= pageContext.getAttribute("com.mycompany.name2", PageContext.REQUEST_SCOPE) %> <%= pageContext.getAttribute("com.mycompany.name3", PageContext.SESSION_SCOPE) %> <%= pageContext.getAttribute("com.mycompany.name4", PageContext.APPLICATION_SCOPE) %>See also e1067 Saving Data Using JSTL in a JSP Page.
e1047. Running Java Code in a JSP Page e1049. Implementing a Form in a JSP Page e1050. Implementing a Form That Prevents Duplicate Submissions in a JSP Page e1051. Precompiling a JSP Page e1052. Preventing the Creation of a Session in a JSP Page
© 2002 Addison-Wesley. |