在Application中获取ServletContext

Ind*_*ous 17 java jax-rs jersey

您能否解释一下我如何ServletContext在我Application的子类中获取实例?可能吗?我试图像在下面的代码片段中那样做,但它似乎不起作用 - ctx没有设置:

import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;

//...

@ApplicationPath("/")
public class MainApplication extends Application {

    @Context ServletContext ctx;

    @Override
    public Set<Class<?>> getClasses() {     
        Set<Class<?>> classes = new HashSet<Class<?>>();
//...
        return classes;
    }
}
Run Code Online (Sandbox Code Playgroud)

web.xml中:

<web-app ...>
 <context-param>
  <param-name>environment</param-name>
  <param-value>development</param-value>
 </context-param>
 <filter>
  <filter-name>jersey-filter</filter-name>
  <filter-class>org.glassfish.jersey.servlet.ServletContainer</filter-class>
   <init-param>
   <param-name>javax.ws.rs.Application</param-name>
   <param-value>my.MainApplication</param-value>
  </init-param>
</filter>
...
</web-app>
Run Code Online (Sandbox Code Playgroud)

问题是我需要从中获取上下文参数.如果有另一种方式,如果有人提示,我将不胜感激.


我知道Context注释可能不适用于此.实际上,我不需要ServletContext自己.如果我只能从web.xml获取上下文参数,我会非常高兴.

这是我真正需要的一个例子:

import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;

import org.glassfish.hk2.utilities.binding.AbstractBinder;

public class MainApplication extends Application {

    @Context ServletContext ctx;

    @Override
    public Set<Object> getSingletons() {
        Set<Object> set = new HashSet<Object>();
        final String environment = ctx.getInitParameter("environment");
        //final String environment = ... get context parameter from web xml
        set.add(new AbstractBinder() {

            @Override
            protected void configure() {
                bind(new BaseDataAccess(environment)).to(DataAccess.class);             
            }
        });
        //...
        return set;
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

Lau*_*uel 16

从Jersey 2.5开始,ServletContext可以直接在构造函数中注入:https: //java.net/jira/browse/JERSEY-2184

public class MyApplication extends ResourceConfig {
    public MyApplication(@Context ServletContext servletContext) {
       // TODO
    }
}
Run Code Online (Sandbox Code Playgroud)