Knowledgebase: Java/JSP Hosting Plans
Saving Data in a JSP Page
Posted by Customer Service on 25 May 2005 12:54 AM
When 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) %>
(510 vote(s))
Not helpful

Comments (0)