简体   繁体   中英

How do I perform one time actions in a Java Webapp AFTER all servlets have been initialized?

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.

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."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM