在JAVA中使用注释启动时加载 [英] Load On Start Up using Annotation in JAVA

查看:888
本文介绍了在JAVA中使用注释启动时加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码,

@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");
  }

}

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

But the servlet doesn't start when the web application is started.

如何在Servlet Annotation上启动加载?

How use load on startup on Servlet Annotation?

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

My Servlet API is 3.0 and I use Tomcat 7

推荐答案

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

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

如果你想在servlet的启动时做一些事情(即元素 loadOnStartup 值大于或等于零, 0 ),您需要将代码放在init方法或servlet的构造函数中:

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");
}






可能更方便使用侦听器在应用程序范围中启动资源(在 ServletContext 中)。


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");
    }

}

例如,请参阅我的回答对于 在JAX-RS请求之间共享变量 的问题。

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

这篇关于在JAVA中使用注释启动时加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆