Home > Back-end >  How do I perform one time actions in a Java Webapp AFTER all servlets have been initialized?
How do I perform one time actions in a Java Webapp AFTER all servlets have been initialized?

Time:10-14

I have a standard Java 11 Web application, with multiple servlets in it. Some servlets are imported by libraries, others are written within the application itself.

I need to perform a task AFTER all web servlets have been initialized, preferably before any requests come in. The task requires access to ServletContext.

I have tried performing this by creating a ServletContextListener and it's corresponding contextInitialized method, but this performs the task BEFORE the servlets have been initialized.

I cannot add the task to the last servlet to load, as the last servlet loaded is imported from an external library.

It would be preferable if the solution does not involve creating a servlet with no mapping.

CodePudding user response:

If you have access to your deployment descriptor (web.xml) and the servlets are eager loaded, then you could append your servlet in the servlet list and set a high number in load-on-startup element.

<servlet>  
    <servlet-name>myServlet</servlet-name>  
    <servlet-class>com.project.LastServlet</servlet-class>  
    <load-on-startup>99</load-on-startup>  
</servlet>

I tried to find a workaround in the documentation, but I couldn't find it and the ServletContextListener is a no go: "All ServletContextListeners are notified of context initialization before any filters or servlets in the web application are initialized."

  • Related