M.J.
M.J.

Reputation: 16646

how to initialize a servlet on sever startup

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

Upvotes: 6

Views: 4171

Answers (2)

JN_newbie
JN_newbie

Reputation: 6062

Use a listener class to invoke a method. For e.g....Define a listener in web.xml file. and give a class name in the listener. And now create a servlet class or java class to write a code to invoke the API.

<web-app>
<listener>
    <listener-class>MyServlet</listener-class>
</listener>

</web-app>

hope this helps out.

Upvotes: 0

planetjones
planetjones

Reputation: 12633

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.

Upvotes: 15

Related Questions