FileDocCategorySizeDatePackage
InitDestroyCounter.javaAPI DocExample2078Tue Jan 25 10:45:14 GMT 2000None

InitDestroyCounter

public class InitDestroyCounter extends HttpServlet

Fields Summary
int
count
Constructors Summary
Methods Summary
public voiddestroy()

    saveState();
  
public voiddoGet(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res)

    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();

    int local_count;
    synchronized(this) {
      local_count = ++count;
      if (count % 10 == 0) saveState();
    }
    out.println("Since loading, this servlet has been accessed " +
                local_count + " times.");
  
public voidinit(javax.servlet.ServletConfig config)

    // Always call super.init(config) first  (servlet mantra #1)
    super.init(config);

    // Try to load the initial count from our saved persistent state
    try {
      FileReader fileReader = new FileReader("InitDestroyCounter.initial");
      BufferedReader bufferedReader = new BufferedReader(fileReader);
      String initial = bufferedReader.readLine();
      count = Integer.parseInt(initial);
      return;
    }
    catch (FileNotFoundException ignored) { }  // no saved state
    catch (IOException ignored) { }            // problem during read
    catch (NumberFormatException ignored) { }  // corrupt saved state

    // No luck with the saved state, check for an init parameter
    String initial = getInitParameter("initial");
    try {
      count = Integer.parseInt(initial);
      return;
    }
    catch (NumberFormatException ignored) { }  // null or non-integer value

    // Default to an initial count of "0"
    count = 0;
  
public voidsaveState()

    // Try to save the accumulated count
    try {
      FileWriter fileWriter = new FileWriter("InitDestroyCounter.initial");
      String initial = Integer.toString(count);
      fileWriter.write(initial, 0, initial.length());
      fileWriter.close();
      return;
    }
    catch (IOException e) {  // problem during write
      // Log the exception.  See Chapter 5.
    }