Custom Servlet Initialization

At the beginning of this chapter, we talked about how a servlet’s persistence can be used to build more efficient web applications. This is accomplished via class variables and the init( ) method. When a server loads a servlet for the first time, it calls the servlet’s init( ) method and doesn’t make any service calls until init( ) has finished. In the default implementation, init( ) simply handles some basic housekeeping, but a servlet can override the method to perform whatever one-time tasks are required. This often means doing some sort of I/O-intensive resource creation, such as opening a database connection. You can also use the init( ) method to create threads that perform various ongoing tasks. For instance, a servlet that monitors the status of machines on a network might create a separate thread to periodically ping each machine. When an actual request occurs, the service methods in the servlet can use the resources created in init( ). Thus, the status monitor servlet might display an HTML table with the status of the various machines. The default init( ) implementation is not a do-nothing method, so you should remember to always call the super.init( ) method as the first action in your own init( ) routines.[21]

The server passes the init( ) method a ServletConfig object, which can include specific servlet configuration parameters (for instance, the list of machines to monitor). ServletConfig encapsulates the servlet initialization parameters, ...

Get Java Enterprise in a Nutshell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.