Counting Page Hits
A simple page counter can be used to illustrate how the scope affects the lifetime and reach of shared information. The difference between the session and application scopes becomes apparent when you place a counter in each scope. Consider the page shown in Example 10-4.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Counter page</title> </head> <body bgcolor="white"> <%-- Increment counters --%> <c:set var="sessionCounter" scope="session" value="${sessionCounter + 1}" /> <c:set var="applCounter" scope="application" value="${applCounter + 1}" /> <h1>Counter page</h1> This page has been visited <b>${sessionCounter}</b> times within the current session, and <b>${applCounter}</b> times by all users since the application was started. </body> </html>
In Example 10-4, JSTL
<c:set>
actions increment counters in the session and application scopes.
Note how each counter variable is placed in a specific scope using
the scope
attribute. The variable placed in the
session scope is found every time the same browser requests this
page, and therefore counts hits per browser. The application scope
variable, on the other hand, is shared by all users, so it counts the
total number of hits for this page. If you run this example, you
should see a page similar to Figure 10-6.
Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.