import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class InitCounter extends HttpServlet { int count; public void init(ServletConfig config) throws ServletException { super.init(config); String initial = config.getInitParameter( initial ); try { count = Integer.parseInt(initial); } catch (NumberFormatException e) { count = 0; } } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType( text/plain ); PrintWriter out = res.getWriter(); count++; out.println( Since loading (and with a possible initialization ); out.println( parameter figured in), this servlet has been accessed ); out.println(count + times. ); } } The init()method accepts an object that implements the ServletConfiginterface. It uses the config object’s getInitParameter()method to get the value for the init parameter named initial. This method takes the name of the parameter as a Stringand returns the value as a String. There is no way to get the value as any other type. This servlet therefore converts the Stringvalue to an intor, if there’s a problem, defaults to a value of O. Take special note that the first thing the init()method does is call super.init(config). Every servlet’s init() method must do this! Why must the init()method call super.init(config)? The reason is that a servlet is passed its ServletConfiginstance in its init()method, but not in any other method. This could cause a problem for a servlet that needs to access its config object outside of init(). Calling super.init(config)solves this problem by invoking the init()method of GenericServlet, which saves a reference to the config object for future use. So, how does a servlet make use of this saved reference? By invoking methods on itself. The GenericServletclass itself implements the ServletConfiginterface, using the saved config object in the implementation. In other words, after the call to super.init(config), a servlet can invoke its own getInitParameter()method. That means we could replace the following call: String initial = config.getInitParameter(”initial”); with: String initial = getInitParameter(”initial”);
Note: If you are looking for good and affordable webspace to host and run your servlet application check Sandzak servlet hosting services