在JAVA中使用注释启动时加载

Die*_*ves 13 java tomcat annotations servlets

我有这个代码,

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

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
      System.out.println("HEREEEE");
  }

}
Run Code Online (Sandbox Code Playgroud)

但是,当Web应用程序启动时,servlet无法启动.

如何在Servlet Annotation上启动加载?

我的Servlet API是3.0,我使用Tomcat 7

Pau*_*gas 13

使用当前代码,您需要执行GET请求以查看输出HEREEEE.

如果要在servlet启动时执行某些操作(即loadOnStartup值大于或等于零的元素0),则需要将代码放在init方法或servlet的构造函数中:

@Override
public void init() throws ServletException {
    System.out.println("HEREEEE");
}
Run Code Online (Sandbox Code Playgroud)

使用侦听器在应用程序范围(在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");
    }

}
Run Code Online (Sandbox Code Playgroud)

有关示例,请参阅我对JAX-RS请求之间共享变量的问题的回答.


Ilj*_*ati 5

@WebServlet(name="InitializeResources", urlPatterns="/initializeResources", loadOnStartup=1)
Run Code Online (Sandbox Code Playgroud)

urlPatterns确保web conatainer找到servlet路径.