import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class InitDestroyCounter extends HttpServlet { int count; public void init(ServletConfig config) throws ServletException { // 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("classes/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 void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); int local_count; synchronized(this) { local_count = ++count; if (count % 10 == 0) saveState(); } out.println("Since the beginning, this servlet has been accessed " + local_count + " times."); } public void destroy() { saveState(); } public void saveState() { // Try to save the accumulated count try { FileWriter fileWriter = new FileWriter("classes/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. } } }