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()?
I am new to Servlets. I want to use a method which is called
Share
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
ServletContextListenerfor this. You can do the initialization stuff in thecontextInitialized()method.If you’re not on
Servlet 3.0yet and can’t upgrade, and thus can’t use@WebListenerannotation, then you need to manually register it in/WEB-INF/web.xmllike below: