在 Jersey Web 应用程序中创建一个主要方法

Create a main method in a Jersey web application

我使用 Jersey 和 Maven 创建了一个 Web 应用程序,我想在服务器启动时执行一些代码,而不是在调用函数时执行。

@Path("/Users") 
public class User {

    public static void main(String[] args) throws InterruptedException {    
            System.out.println("Main executed");
           //I want to execute some code here
    }

    @GET
    @Path("/prof") 
    @Produces(MediaType.APPLICATION_JSON)
    public List<String> getFile(@QueryParam("userid") String userid, {

但是 main 方法从未执行过,我从未看到输出 Main executed。 我也尝试用普通的 main 方法创建一个新的 class,但它也从未执行过。

您需要创建一个 ServletContextListener 实现,并将其注册到您的 web.xml 文件中:

ApplicationServletContextListener.java:

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ApplicationServletContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("Application started");  
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
    }
}

web.xml:

<web-app>
  <listener>
    <listener-class>
      com.yourapp.ApplicationServletContextListener
    </listener-class>
  </listener>
</web-app>

如果使用 servlet 3.0,您也可以只用 @WebListener 注释来注释 class 而不是在 web.xml 文件中注册它。


或者,正如另一位用户指出的那样,Jersey 包含一个 ApplicationEventListener,您可以在应用程序初始化后使用它来执行操作:

MyApplicationEventListener.java:

public class MyApplicationEventListener implements ApplicationEventListener {

    private volatile int requestCount = 0;

    @Override
    public void onEvent(ApplicationEvent event) {
        switch (event.getType()) {
            case INITIALIZATION_FINISHED:
                System.out.println("Application was initialized.");
                break;
            case DESTROY_FINISHED:
                System.out.println("Application was destroyed.");
                break;
        }
    }

    @Override
    public RequestEventListener onRequest(RequestEvent requestEvent) {
        requestCount++;
        System.out.println("Request " + requestCount + " started.");

        // return the listener instance that will handle this request.
        return new MyRequestEventListener(requestCnt);
    }
}

请注意,这不是 JAX-RS 标准的一部分,并且会将您的应用程序与使用 Jersey 联系起来。