Java Reference
In-Depth Information
later in the chapter.) Finally, if the servlet cannot find a counter name using either
of these techniques, it uses the URL through which it was invoked as the counter
name. As you'll see shortly, the servlet container can be configured to invoke the
servlet in response to any URL that ends with the suffix .count .
Note that the doGet() method contains a synchronized block of code. The Servlet
API allows multiple threads to execute the body of doGet() at the same time. Even
though many threads representing many different user sessions may be running,
they all share a single data structure—the hashtable of named counts. The syn-
chronized block prevents the threads from accessing (and possibly corrupting) the
shared data structure at the same time. Finally, note the use of the log() method.
When asked to start counting with a counter name it has never used before, the
servlet uses this method to produce a permanent record of the event in a log file.
Example 18−2: Counter.java
package com.davidflanagan.examples.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
/**
* This servlet maintains an arbitrary set of counter variables and increments
* and displays the value of one named counter each time it is invoked. It
* saves the state of the counters to a disk file, so the counts are not lost
* when the server shuts down. It is suitable for counting page hits, or any
* other type of event. It is not typically invoked directly, but is included
* within other pages, using JSP, SSI, or a RequestDispatcher
**/
public class Counter extends HttpServlet {
HashMap counts;
// A hash table: maps counter names to counts
File countfile;
// The file that counts are saved in
long saveInterval;
// How often (in ms) to save our state while running?
long lastSaveTime;
// When did we last save our state?
// This method is called when the web server first instantiates this
// servlet. It reads initialization parameters (which are configured
// at deployment time in the web.xml file), and loads the initial state
// of the counter variables from a file.
public void init() throws ServletException {
ServletConfig config = getServletConfig();
try {
// Get the save file.
countfile = new File(config.getInitParameter("countfile"));
// How often should we save our state while running?
saveInterval =
Integer.parseInt(config.getInitParameter("saveInterval"));
// The state couldn't have changed before now.
lastSaveTime = System.currentTimeMillis();
// Now read in the count data
loadState();
}
catch(Exception e) {
// If something goes wrong, wrap the exception and rethrow it
throw new ServletException("Can't init Counter servlet: " +
e.getMessage(), e);
}
Search WWH ::




Custom Search