Saturday, 3 May 2014

Servlets : load-on-startup - Example

🚀 Master Java & Boost Your Coding Skills!

Subscribe to Ram N Java for crystal-clear programming tutorials and step-by-step guides.

🔔 Subscribe Now

What is Load-on-Startup in Java Servlets?

By default, a servlet is loaded and initialized by the servlet container (like Apache Tomcat) lazily—only when the first request for that servlet is received. However, using the <load-on-startup> element in your web.xml, you can instruct the container to load and initialize (call init()) the servlet automatically at the time of application deployment or server startup.

How the Load-on-Startup Order Works

The value specified inside <load-on-startup> determines the priority order in which servlets are initialized:

  • Zero or Positive Integer (e.g., 0, 1, 2): Servlets are initialized in ascending order (0 first, then 1, then 2).
  • Negative Integer or Not Specified: The servlet container initializes the servlet on demand when the first request arrives.

Practical Example Breakdown

In this demo, three servlets are configured in web.xml:

  • HelloWorld Servlet: <load-on-startup>0</load-on-startup> → Initialized 1st during server startup.
  • ServletLifeCycle Servlet: <load-on-startup>1</load-on-startup> → Initialized 2nd during server startup.
  • CustomerInfo Servlet: No <load-on-startup> defined → Initialized only when first requested via the form submission.

Why Use Load-on-Startup?

  • Faster First Request: Eliminates initial latency for users because the servlet is already initialized in memory.
  • Preloading Resources: Ideal for loading database connection pools, configuration files, and caching heavy data upfront.

Recommended Related Tutorials

1 comment:

  1. Nice Article. Thank you for sharing the informative article with us. biznesshub.

    ReplyDelete

Tutorials