} public void doGet(HttpServletRequest req, HttpServletResponse res) throws
} public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType( text/plain ); PrintWriter out = res.getWriter(); count++; out.println( Since the beginning, this servlet has been accessed + count + times. ); } public void destroy() { saveState(); } public void saveState() { // 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. Example 3-4. A fully persistent counter (countinued) } } } Each time this servlet is about to be unloaded, it saves its state in a file named InitDestroyCounter.initial. In the absence of a supplied path, the file is saved in the server process’ current directory, usually the server_root.* This file contains a single integer, saved as a string, that represents the latest count. Each time the servlet is loaded, it tries to read the saved count from the file. If, for some reason, the read fails (as it does the first time the servlet runs because the file doesn’t yet exist), the servlet checks if an init parameter specifies the starting count. If that too fails, it starts fresh with zero. You can never be too careful in init() methods. Servlets can save their state in many different ways. Some may use a custom file format, as was done here. Others may save their state as serialized Java objects or put it into a database. Some may even perform journaling, a technique common to databases and tape backups, where the servlet’s full state is saved infrequently while a journal file stores incremental updates as things change. Which method a servlet should use depends on the situation. In any case, you should always be watchful that the state being saved isn’t undergoing any change in the background.
Note: If you are looking for best hosting provider to host and run your tomcat application check Astra tomcat hosting services