Java.Servlet.How can you implement servlet startup at the same time as the application startup?

If you want your servlet to initialize immediately when the web application starts (instead of waiting for the first request), the solution is simple and powerful:


✅ Use load-on-startup in web.xml

This tells the servlet container to load and initialize the servlet when the application starts, not lazily on first request.

📄 Example web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
  <servlet>
    <servlet-name>InitServlet</servlet-name>
    <servlet-class>com.myapp.InitServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>InitServlet</servlet-name>
    <url-pattern>/init</url-pattern>
  </servlet-mapping>
</web-app>

🔢 How load-on-startup Works:

  • The value is an integer (1, 2, etc.)
  • Lower values load earlier
  • Any non-negative value means: load at startup
  • -1 (or no tag) = lazy loading (default behavior)

🧪 What Happens at Startup?

  • The servlet container loads your class
  • Instantiates the servlet
  • Calls its init() method
  • You can place any startup logic here (DB init, config loading, etc.)

🔧 Servlet Code

public class InitServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        System.out.println("🚀 InitServlet initialized at app startup!");
        // Perform startup tasks here
    }
}

✅ Alternative (Modern Way): Use @WebServlet with loadOnStartup

If you’re using annotations (Servlet 3.0+):

@WebServlet(urlPatterns = "/init", loadOnStartup = 1)
public class InitServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        System.out.println("🚀 InitServlet started with app!");
    }
}

💡 When to Use Servlet Startup Initialization

  • Initialize app-wide resources (DB pools, config, background threads)
  • Trigger a background task
  • Log deployment details
  • Perform license or health checks

✅ Summary

TechniqueHowNotes
web.xml<load-on-startup>1</load-on-startup>Classic config
Annotation-based servlet@WebServlet(..., loadOnStartup=1)Modern approach
Lifecycle hook (alternative)ServletContextListener.contextInitialized()For general app-wide init
This entry was posted in Без рубрики. Bookmark the permalink.