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

查看:34
本文介绍了使用 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");
  }

}

但是当 Web 应用程序启动时 servlet 没有启动.

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天全站免登陆