FileDocCategorySizeDatePackage
LifeCycleServlet.javaAPI DocExample2086Wed Apr 05 11:25:42 BST 2000None

LifeCycleServlet.java

/*
 * This example is from the book "Java Enterprise in a Nutshell".
 * Copyright (c) 1999 by O'Reilly & Associates.  
 * You may distribute this source code for non-commercial purposes only.
 * You may study, modify, and use this example for any purpose, as long as
 * this notice is retained.  Note that this example is provided "as is",
 * WITHOUT WARRANTY of any kind either expressed or implied.
 */

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class LifeCycleServlet extends HttpServlet {

  int timesAccessed;

  public void init(ServletConfig conf) throws ServletException {

    super.init(conf);

    // Get initial value
    try {
      timesAccessed = Integer.parseInt(getInitParameter("defaultStart"));
    } 
    catch(NullPointerException e) {
     timesAccessed = 0;
    } 
    catch(NumberFormatException e) {
      timesAccessed = 0;
    }

    // Try loading from the disk
    try {
      File r = new File("./data/counter.dat");      
      DataInputStream ds = new DataInputStream(new FileInputStream(r));
      timesAccessed = ds.readInt();
      ds.close();
    } 
    catch (FileNotFoundException e) {
      // Handle error
    } 
    catch (IOException e) {
      // This should be logged
    }    

  }
        
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
  
    timesAccessed++;
   
    out.println("<HTML>");
    out.println("<HEAD>");
    out.println("<TITLE>Life Cycle Servlet</TITLE>");
    out.println("</HEAD><BODY>");
     
    out.println("I have been accessed " + timesAccessed + " time[s]");
    out.println("</BODY></HTML>"); 
  }

  public void destroy() {

    // Write the Integer to a file
    File r = new File("./data/counter.dat");
    try {
      DataOutputStream dout = new DataOutputStream(new FileOutputStream(r));
      dout.writeInt(timesAccessed);
      dout.close();
    } 
    catch(IOException e) {
      // This should be logged 
    }

  }
}