Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can load-on-startup in web.xml be used to load an arbitrary class on startup?

How can I load an arbitrary class on startup in Tomcat? I saw load-on-startup tag for web.xml file, but can I use it and how should I implement my class?

<servlet-name>??</servlet-name>
<servlet-class>??</servlet-class>
<load-on-startup>10</load-on-startup>
like image 852
enfix Avatar asked Jul 20 '10 12:07

enfix


People also ask

What does load-on-startup element in Web XML do?

The load-on-startup element of web-app loads the servlet at the time of deployment or server start if value is positive. It is also known as pre initialization of servlet. You can pass positive and negative value for the servlet.

What is use of load-on-startup?

The <load-on-startup> element indicates that the servlet should be loaded on the startup of the web application. The optional contents of this element must be a positive integer that specifies the order in which the servlet should be loaded. Servlets with lower values are loaded before servlets with higher values.

What is load-on-startup in Spring MVC?

The element content of 'load-on-startup' is Integer. if the integer is negative: The container loads servlet at any time. if the integer is 0 or positive: The servlet marked with lower integers are loaded before servlets marked with higher integers.

Which of the following element can be used in the Web XML to configure pre initialization?

init-param This is an element within the servlet. The optional init-param element contains a name/value pair as an initialization attribute of the servlet. Use a separate set of init-param tags for each attribute.


1 Answers

Those are meant to specify the loading order for servlets. However, servlets are more meant to control, preprocess and/or postprocess HTTP requests/responses while you sound like to be more looking for a hook on webapp's startup. In that case, you rather want a ServletContextListener.

@WebListener
public class Config implements ServletContextListener {
    public void contextInitialized(ServletContextEvent event) {
        // Do your thing during webapp's startup.
    }
    public void contextDestroyed(ServletContextEvent event) {
        // Do your thing during webapp's shutdown.
    }
}

If you're not on Servlet 3.0 yet (and thus can't use @WebListener), then you need to manually register it in web.xml as follows:

<listener>
    <listener-class>com.example.Config</listener-class>
</listener>

See also:

  • Servletcontainer lifecycle
like image 51
BalusC Avatar answered Sep 22 '22 13:09

BalusC