In the beginning: loading and initializing
The servlet starts life when the Container finds the servlet class file. This virtually always happens when the Container starts up (for example, when you run Tomcat). When the Container starts, it looks for deployed web apps and then starts searching for servlet class files. (In the Deployment chapter, we’ll go into more details of how, why, and where the Container looks for servlets.)
Finding the class is the first step.
Loading the class is the second step, and it happens either on Container startup or first client use. Your Container might give you a choice about class loading, or it might load the class whenever it wants. Regardless of whether your Container gets the servlet ready early or does it just-in-time when the first client needs it, a servlet’s service() method will not run until the servlet is fully initialized.
Your servlet is always loaded and initialized BEFORE it can service its first client request.
init() always completes before the first call to service()
Flex Your Mind
Why is there an init() method? In other words, why isn’t the constructor enough for initializing a servlet?
What kind of code would you put in the init() method?
Hint: the init() method takes an object reference argument. What do you think the argument to the init() method might be, and how (or why) would you use it?
Servlet Initialization: when an object becomes a servlet
A servlet moves from does not exist to initialized (which really means ready to service ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access