The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Servlets
Lesson: The Servlet Life Cycle

Initializing a Servlet

The default initialization of the HttpServlet class initializes the servlet and logs the initialization. To add initialization specific to your servlet, override the init method. When you override the init method, follow these rules:
 

Here is an example init method:

public class BookDetailServlet ... {

    public void init() throws ServletException {
        BookDBFrontEnd bookDBFrontEnd =
            (BookDBFrontEnd)getServletContext().getAttribute(
                "examples.bookstore.database.BookDBFrontEnd");

        if (bookDBFrontEnd == null) {
            getServletContext().setAttribute(
                "examples.bookstore.database.BookDBFrontEnd",
                BookDBFrontEnd.instance());
        }
        ...
    }

The init method is straightforward: it tries to get an attribute, and if the attribute does not yet have a value, it provides one.

There are other initialization tasks that a servlet might perform. If a servlet used a database, for example, the init method could try to open a connection and throw the UnavailableException if it was unsuccessful. Here is pseudo-code for what that init method might look like:

    public class DBServlet ... {

        Connection connection = null;

        public void init() throws ServletException {

            // Open a database connection to prepare for requests
            try {
                databaseUrl = getInitParameter("databaseUrl");
                ... // get user and password parameters the same way
                connection = DriverManager.getConnection(databaseUrl,
                                                         user, password);
            } catch(Exception e) {
                throw new UnavailableException (this,
		    "Could not open a connection to the database");
            }
        }
        ...
    }

 

Initialization Parameters

The second version of the init method calls the getInitParameter method. This method takes the parameter name as an argument and returns a String representation of the parameter's value.

The specification of initialization parameters is servlet engine specific. For example, the parameters are specified with the init-param element in a Java Servlet 2.2 Web application deployment descriptor when a servlet is run with Tomcat and a property when a servlet is run with the JSDK2.1 server. The Utilities for Running Servlets lesson contains a general explanation of how to configure servlet engines.

If, for some reason, you need to get the parameter names, use the getParameterNames method.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2002 Sun Microsystems, Inc. All rights reserved.