O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Servlet Initialization and Persistence: A Counter Servlet

Example 20-3 is a listing of Counter.java, 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required