Configuring servlet initialization in the DD

You already know that servlets, by default, are initialized at first request. That means the first client suffers the pain of class loading, instantiation, and initialization (setting a ServletContext, invoking listeners, etc.), before the Container can do what it normally does— allocate a thread and invoke the servlet’s service() method.

If you want servlets to be loaded at deploy time (or at server restart time) rather than on first request, use the <load-on-startup> element in the DD. Any non-negative value for <load-on-startup> tells the Container to initialize the servlet when the app is deployed (or any time the server restarts).

If you have multiple servlets that you want preloaded, and you want to control the order in which they’re initialized, the value of <load-on-startup> determines the order! In other words, any non-negative value means load early, but the order in which servlets are loaded is based on the value of the different <load-on-startup> elements.

image with no caption

In the DD

image with no caption

Q:

Q: Wouldn’t you ALWAYS want to do this? Shouldn’t everyone just use <load-on-startup>1</load-on-startup> by default?

A:

A: To answer that question, you ask yourself, “How many servlets do I have in my app, and how likely is it that they’ll all be used?” And you’ll also ...

Get Head First Servlets and JSP, 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.