Making a JSP that displays how many times it’s been accessed

Pauline wants to use JSPs in her web apps—she’s really sick of writing HTML into a servlet’s PrintWriter println().

She decides to learn JSPs by making a simple dynamic page that prints the number of times the page has been requested. She understands that you can put regular old Java code in a JSP using a scriptlet—which just means Java code within a <% ... %> tag.

image with no caption

BasicCounter.jsp

image with no caption

Counter.java

package foo;

public class Counter {
   private static int count;
   public static synchronized int getCount() {
      count++;
      return count;
   }
}

Note

Plain old Java helper class.

Get Head First Servlets and JSP, 2nd 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.