Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Using Sessions, Applications, and JavaBeans

It turns out that you can instruct Tomcat to save JavaBeans in a session object as well as in attributes. In fact, you can store JavaBeans in applications as well. You do this with the <jsp:useBean> element's scope attribute, which you can set to one of these values: scope="page|request|session|application". The term scope indicates where a data item is "visible" (meaning it may be referred to by name) in your code. The default scope for a bean is page scope, which means the bean exists only for the page scope. However, if you set the scope of a bean to session, it is stored with the rest of the session's data.

The bean you see in Listing 7.7 maintains a property named counter that JSP code can increment—we'll see that using page scope, counter is reset to 1 each time the page loads, but using session scope, counter will increment to 2, 3, 4, and so on as you reload the page, because the bean is stored in the session's data.

Listing 7.7 A Bean That Maintains a Usage Counter (ch07_07.jsp)

package beans;

public class ch07_07
{

  private int counter = 0;

  public void setCounter(int value) 
  {
    this.counter = value;
  }

  public int getCounter() 
  {
    return this.counter;
  }

  public ch07_07() 
  {
  }
}

You can see a JSP page that uses this bean with page scope in Listing 7.8.

Listing 7.8 Using Page Scope for Beans (ch07_08.jsp)

<HTML>
  <HEAD>
    <TITLE>Using Beans and Page Scope</TITLE>
  </HEAD>

  <BODY>
    <H1>Using Beans and Page Scope</H1>

    <jsp:useBean id="bean1" class="beans.ch07_07" scope="page" />

    <% 
    bean1.setCounter(bean1.getCounter() + 1);
    %>
    The counter value is: <jsp:getProperty name="bean1" property="counter" /> 
  </BODY>
</HTML>

And you can see that Web page at work in Figure 7.9—no matter how many times you reload this page, the counter will remain set to 1, because the bean has page scope, so it's created anew each time you load the page.

Figure 7.9Figure 7.9 Using a bean with page scope.

However, if you give the bean session scope, as in Listing 7.9, it's stored with the rest of the session, which means the counter value will be preserved between page accesses.

Listing 7.9 Using Session Scope for Beans (ch07_09.jsp)

<HTML>
  <HEAD>
    <TITLE>Using Beans and Session Scope</TITLE>
  </HEAD>

  <BODY>
    <H1>Using Beans and Session Scope</H1>

    <jsp:useBean id="bean1" class="beans.ch07_07" scope="session" />

    <% 
    bean1.setCounter(bean1.getCounter() + 1);
    %>
    The counter value is: <jsp:getProperty name="bean1" property="counter" /> 
  </BODY>
</HTML>

You can see the results of giving the bean session scope in Figure 7.10.

Figure 7.10Figure 7.10 Using a bean with session scope.

  • + Share This
  • 🔖 Save To Your Account