Get ServletContext in Application

前端 未结 6 701
长情又很酷
长情又很酷 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:31

    @Context can be made available on ResoureConfig by injecting it as a constructor parameter using @Context. Another way to access it is through an event handler.

    Try the below code.

    @ApplicationPath("...")
    public class MyApplication extends ResourceConfig {
        public MyApplication() {
            register(StartupHandler.class);
        }
    
        private static class StartupHandler extends  AbstractContainerLifecycleListener {
            @Context
            ServletContext ctx;
    
            @Override
            public void onStartup(Container container) {
                // You can put code here for initialization. 
            }
        }
    // ...
    

提交回复
热议问题