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 does not 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(ServletConfig) implementation is not a do-nothing method, so you should remember to always call the super.init(ServetConfig) method. If you override the parameterless version, you don’t have to invoke the superclass’s method—the server calls the parameterized version, which calls the parameterless method. You can access the ServletConfig object using the getServletConfig() method.

The server passes ...

Get Java Enterprise in a Nutshell, Third 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.