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.

Example 10-4. A page with counter beans (counter1.jsp)
<%@ taglib prefix="c" uri="" %>
    <title>Counter page</title>
  <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.

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.

A page with session and application page hit counters
Figure 10-6. A ...

Get JavaServer Pages, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.