A JSP Hit Counter
Home ] Up ] What's  a Java Server Page? ] How Does a JSP Work? ] Do JSPs Replace Servlets? ] JSP Expressions vs. Scriplets ] Conditional JSPs ] JSP Declarations ] [ A JSP Hit Counter ]

 

 

We can use this to implement a hit counter for a JSP page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Hit Counter</title>
  </head>
  <body>
    
    <h1>JSP Hit Counter</h1>
    
    <%! private int counter = 0; %>
    
    <h2>This page has been accessed 
      <span style="color:red">
        <%= ++counter %>
      </span>
    times since the server was rebooted</h2>
    
  </body>
</html>

Here is what it displays after a number of accesses:

 
The page was last updated February 19, 2008