Chapter 3. The Servlet Lifecycle

The servlet lifecycle is one of the most exciting features of servlets. This lifecycle is a powerful hybrid of the lifecycles used by CGI programming and lower-level WAI/NSAPI and ISAPI programming, as discussed in Chapter 1.

The Servlet Alternative

The servlet lifecycle allows servlet containers to address both the performance and resource problems of CGI and the security concerns of low-level server API programming. A common way to execute servlets is for the servlet container to run all its servlets in a single Java Virtual Machine ( JVM). By placing all the servlets into the same JVM, the servlets can efficiently share data with one another, yet they are prevented by the Java language from accessing one another’s private data. Servlets can persist between requests inside the JVM as object instances. This takes up far less memory than full-fledged processes, yet servlets still are able to efficiently maintain references to external resources.

The servlet lifecycle is highly flexible. The only hard and fast rule is that a servlet container must conform to the following lifecycle contract:

  1. Create and initialize the servlet.

  2. Handle zero or more service calls from clients.

  3. Destroy the servlet and then garbage collect it.

It’s perfectly legal for a servlet to be loaded, created, and instantiated in its own JVM, only to be destroyed and garbage collected without handling any client requests or after handling just one request. Any servlet container that ...

Get Java Servlet Programming, 2nd 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.