Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to initialize a servlet on sever startup

Tags:

java

servlets

I have written a simple servlet with init() and doGet(), doPost() method. I have a requirement, that I have an API which i need to invoke an server startup.

Is it possible to do so. I tried with init method, and setting default values in web.xml, but i am still unable to do so.

Please tell if I am missing something.

Thanks

like image 249
M.J. Avatar asked Jun 20 '11 15:06

M.J.


People also ask

How are servlets loaded 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.

How would you pre initialize a servlet?

Some ways to preinitialize a servlet are: To use the tag non-zero-integer with the deployment descriptor web. xml which loads and initialises the servlet when the server starts. 3. To load a servlet in order of number specified.

How are servlets initialized?

The servlet is initialized by calling the init() method. The servlet calls service() method to process a client's request. The servlet is terminated by calling the destroy() method. Finally, servlet is garbage collected by the garbage collector of the JVM.

When can a servlet be loaded?

As you know well, servlet is loaded at first request. That means it consumes more time at first request. If you specify the load-on-startup in web. xml, servlet will be loaded at project deployment time or server start.


1 Answers

Have you set the load-on-startup attribute to be positive?

<servlet id=”servlet1”>
<load-on-startup>2</load-on-startup>
</servlet>

Alternatively, you might want to use a ServletContextListener to do initialisation work when the container comes up. This is the 'de facto' standard for having a callback to do some initialisation work when the servlet container comes online e.g. we use that to read in some XML files and populate a cache.

like image 120
planetjones Avatar answered Nov 14 '22 20:11

planetjones