Java Reference
In-Depth Information
page
Scope
Beans with
page
scope are accessible only within the page where they were created.
References to an object with
page
scope will be released when the response is sent back to the
client or the request is forwarded to another resource. Objects with
page
scope are stored in the
pageContext
. A bean with
page
scope is most often used for single instance calculations or
transactions.
An example of using the
Counter
bean with
page
scope can be found in Listing 17.2.
17
L
ISTING
17.2
PageBean.jsp
<%@ page errorPage=”errorpage.jsp” %>
<!-- Instantiate the Counter bean with an id of “counter” -->
<jsp:useBean id=”counter” scope=”page” class=”Counter” />
<html>
<head>
<title>Page Bean Example</title>
</head>
<body>
<H3>Page Bean Example</H3>
<center><b>The current count for the counter bean is: </b>
<%=counter.getCount() %></center>
</body>
</html>
You can see that this JSP creates an instance of the
Counter
bean with an
id
of
“counter”
. It
then prints the current value of the bean's
count
property.
To test the
page
scope example, move the
PageBean.jsp
to the
<
SERVER_ROOT
>/djs/
directory
and open your browser to the following URL:
http://
localhost
/djs/PageBean.jsp
You should see a page similar to Figure 17.1.
Go ahead and reload the page a few times. You will notice that the printed count is always
reset to 1. This is because each instance of the
counter
bean is new every time the page is
loaded.