Get ServletContext in Application

前端 未结 6 699
长情又很酷
长情又很酷 2020-12-29 07:06

Could you possibly explain how I can get the ServletContext instance in my Application\'s sub-class? Is it possible? I have tried to do it like in

6条回答
  •  臣服心动
    2020-12-29 07:28

    You can use the ApplicationEventListener interface to get the ServletContext. After initialization has finished, you can 'catch' an ApplicationEvent and use the injected ServletContext to work with.

    Works fine with: org.glassfish.jersey : 2.12
    For additional versions, pls use comments - i dont know, sry.

    Jersey Docs - 20.1.2. Event Listeners

    Your MainApplication:

    @ApplicationPath("/")
    public class MainApplication extends Application {
        @Override
        public Set> getClasses() {     
            Set> set = new HashSet>();
            set.add(MainApplicationListener.class);
            return classes;
        }
    }
    

    ... or alternative MainResourceConfig (I prefer to use this one):

    public class MainResourceConfig extends ResourceConfig {
        public MainResourceConfig() {
            register(MainApplicationListener.class);
        }
    }
    

    And the ApplicationEventListener:

    public class MainApplicationListener implements ApplicationEventListener {
    
        @Context
        private ServletContext ctx; //not null anymore :)
    
        @Override
        public void onEvent(ApplicationEvent event) {
            switch (event.getType()) {
                case INITIALIZATION_FINISHED:
                // do whatever you want with your ServletContext ctx
                break;
        }
    
        @Override
        public RequestEventListener onRequest(RequestEvent requestEvent) {
            return null;
        }
    
    }
    

提交回复
热议问题