Tomcat Java Servlet - Initialize Class on Application Startup

試著忘記壹切 提交于 2019-11-30 09:07:26

You have two choices:

  1. Initialize your class in servlet's init() method. You may add <load-on-startup> attribute to make sure your servlet is created at application startup and not on first access.

  2. Add ServletContextListener and use contextInitialized() callback method. Use ServletContext#setAttribute to store created object for future use.

If you want it to happen once for the whole app, and happen before any servlet is run, implement ServletContextListener and put your startup code in contextInitialized(). Then set up your web.xml to specify your class as a listener.

Otherwise, you can do what the other answer says and put it in the init() method of the servlet.

You can do the initialize of the class inside the servlet's init method.
init() method is invoked when the servlet instance is loaded so it is a good place for expensive operations.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!