This second style works even outside of the

This second style works even outside of the init()method. Just remember, without the call to super.init(config)in the init()method, any call to the GenericServlet’s implementation of getInitParameter()or any other ServletConfigmethods will throw a NullPointerException. So, let us say it again: every servlet’s init() method should call super.init(config) as its first action. The only reason not to is if the servlet directly implements the javax.servlet.Servletinterface, where there is no super.init(). A Counter with Init and Destroy Up until now, the counter examples have demonstrated how servlet state persists between accesses. This solves only part of the problem. Every time the server is shut down or the servlet is reloaded, the count begins again. What we really want is persistence across loads a counter that doesn’t have to start over. The init()and destroy()pair can accomplish this. Example 3-4 further extends the InitCounter example, giving the servlet the ability to save its state in destroy()and load the state again in init(). To keep things simple, assume this servlet is not registered and is accessed only as http://server:port/servlet/InitDestroyCounter. If it were registered under different names, it would have to save a separate state for each name. Example 3-4. A fully persistent counter 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); Example 3-4. A fully persistent counter (countinued) // 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;

Hint: This post is supported by Gama php5 hosting services

Comments are closed.