Load On Start Up using Annotation in JAVA

后端 未结 3 1163
离开以前
离开以前 2021-01-04 04:18

I have this code,

@WebServlet(value=\"/initializeResources\", loadOnStartup=1)
public class InitializeResources extends HttpServlet {

  @Override
  protecte         


        
3条回答
  •  臣服心动
    2021-01-04 05:02

    With you current code, you need to do a GET request for see the output HEREEEE.

    If you want to do something on the startup of the servlet (i.e. the element loadOnStartup with value greater or equal to zero, 0), you need put the code in a init method or in the constructor of the servlet:

    @Override
    public void init() throws ServletException {
        System.out.println("HEREEEE");
    }
    

    It may be more convenient to use a listener to start a resource in the application scope (in the ServletContext).

    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import javax.servlet.annotation.WebListener;
    
    @WebListener
    public class InitializeListener implements ServletContextListener {
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            System.out.println("On start web app");
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            System.out.println("On shutdown web app");
        }
    
    }
    

    For an example, see my answer for the question Share variables between JAX-RS requests.

提交回复
热议问题