【问题标题】:Create a main method in a Jersey web application在 Jersey Web 应用程序中创建一个 main 方法
【发布时间】:2016-09-27 08:49:23
【问题描述】:

我使用 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 方法创建一个新类,但它也永远不会执行。

【问题讨论】:

  • 在服务器应用程序中,执行/类加载与控制台/桌面应用程序不同,在 Web 应用程序中,您可以使用具有多个事件的 ApplicationListener,您可能关心的是创建一个实现的类ServletContextListener 并在您的 web.xml 中声明它

标签: java maven jersey main


【解决方案1】:

您需要创建一个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 注释来注释类,而不是在您的 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。

【讨论】:

    猜你喜欢
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 2018-02-03
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多