O'Reilly logo

Java Enterprise in a Nutshell, Second Edition by David Flanagan, Jim Farley, William Crawford

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required