Search code examples
javamavenjerseyprogram-entry-point

Create a main method in a Jersey web application


I have created a web application using Jersey and Maven, and I want to execute some code when the server starts, not when a function is called.

@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, {

But the main method is never executed, I never see the output Main executed. I have also tried to create a new class with a normal main method, but it also never executes.


Solution

  • You need to create a ServletContextListener implementation, and register it in your web.xml file:

    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>
    

    If using servlet 3.0, you can also just annotate the class with the @WebListener annotation instead of registering it in your web.xml file.


    Alternatively, as another user points out, Jersey includes an ApplicationEventListener that you can use to perform an action once the application is initialized:

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

    Note that this is not part of the JAX-RS standard, and will tie your application to using Jersey.