|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The default initialization of the
HttpServletclass initializes the servlet and logs the initialization. To add initialization specific to your servlet, override theinitmethod appropriate to your version of the JSDK: theinit(ServletConfig)method for version 2.0 and theinit()method for version 2.1. When you override theinitmethod, follow these rules:
- If an initialization error occurs that renders the servlet incapable of handling client requests, throw an
UnavailableException.An example of this type of error is the inability to establish a required network connection.
- Do not call the
System.exitmethod
- For Version 2.0 only: Save the
ServletConfigparameter so that thegetServletConfigmethod can return the value. The simplest way to do this is to have your newinitmethod callsuper.init.Here is an example
initmethod for version 2.1: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
initmethod 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
initmethod could try to open a connection and throw theUnavailableExceptionif it was unsuccessful. Here is pseudo-code for what thatinitmethod 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
initmethod calls thegetInitParametermethod. This method takes the parameter name as an argument and returns aStringrepresentation of the parameter's value.(The specification of initialization parameters is server-specific. For example, the parameters are specified with a property when a servlet is run with
servletrunneror with the JSDK2.1 server. The Utilities for Running Servlets lesson contains a general explanation of properties and how to create them.)If, for some reason, you need to get the parameter names, use the
getParameterNamesmethod.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |