Sun Java System Web Server 7.0 Developer's Guide to Java Web Applications

Overriding init()

Override the class initializer init() to initialize or allocate resources for the servlet instance's life, such as a counter. The init() method runs after the servlet is instantiated but before it accepts any requests. For more information, see the servlet API specification.

Note –

When extending GenericServlet or HttpServlet, you must either override init(ServletConfig) to first call super.init(ServletConfig) or simply override the init() method that takes no arguments. This your servlet's ServletConfig enables be saved locally and later returned by calls to your servlet's getServletConfig() method.

The following example of the init() method initializes a counter by creating a public integer variable called thisMany:

public class myServlet extends HttpServlet {
        int thisMany;
public void init (ServletConfig config) throws ServletException
           thisMany = 0;

This method enables other servlet methods to access the variable.