I am new to Servlets. I want to use a method which is called only once after deploying to server. I looked at HttpServlet#init()
. But I figured out it is called with each request. Did I misunderstand it? What are the alternatives to init()
?
views:
92answers:
3init()
is only called upon creation of the servlet. This may happen multiple times during the life of the server. You use it to initialize any variables or logic required for regular use of the servlet.
Edit: After re-reading your post, it is not technically called with each request because the server is creating a new instance of the servlet for each request. Check your server settings as to whether it will get a new servlet of keep a single servlet for the life of the server.
Are you looking for a ServletContextListener?
http://stackoverflow.com/questions/2057563/how-do-i-run-a-method-before-republishing-to-jboss
No, it is not called in each request. It is only called during initialization of the servlet which usually happens only once in webapp's lifetime. Also see this answer for a bit more detail how servlets are created and executed.
If you actually want to do some global/applicationwide initialization (which is thus not per se tied to only the particular servlet), then you would normally use the ServletContextListener
for this. You can do the initialization stuff in the contextInitialized()
method.
public class Config implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
// Do stuff during webapp's startup.
}
public void contextDestroyed(ServletContextEvent event) {
// Do stuff during webapp's shutdown.
}
}
Just register it in web.xml
as follows to get it to run:
<listener>
<listener-class>com.example.Config</listener-class>
</listener>