Servlet Initialization and Persistence: A Counter Servlet

Example 20-3 is a listing of, a servlet that maintains any number of named counters. Each time the value of one of these counters is requested, the servlet increments the counter and outputs its new value. The servlet is suitable for use as a simple hit counter for multiple web pages but can also count any other type of event.

This servlet defines init( ) and destroy( ) methods and saves its state to a file, so it does not lose count when the web server (or servlet container) shuts down. To understand init( ) and destroy( ), you have to understand something about the servlet life cycle. Servlet instances are not usually created anew for each client request. Instead, once a servlet is created, it can serve many requests before it is destroyed. A servlet such as Counter is typically not shut down unless the servlet container itself is shutting down, or the servlet is inactive and the container is trying to free up memory to make room for other servlets.

The init( ) method is invoked when the servlet container first instantiates the servlet, before any requests are serviced. The first thing this method does is look up the value of two initialization parameters: the filename of the file that contains the saved state and an integer value that specifies how often to save the state back into that file. Once the init( ) method has read these parameters, it reads the counts (using object serialization) from the ...

Get Java Examples in a Nutshell, 3rd Edition now with O’Reilly online learning.

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