Jersey 2:如何将参数从web.xml传递给Application?

时间:2013-10-25 18:01:45

标签: jersey jax-rs jersey-2.0

我的网络容器知道我的应用程序是在调试模式还是在发布模式下运行。我想将此信息传递给我的ResourceConfig / Application类,但目前尚不清楚如何阅读这些信息。

是否可以通过servlet / filter参数传递信息?如果是这样,怎么样?

3 个答案:

答案 0 :(得分:3)

以下是我的表现:

web.xml中的

<context-param>
  <description>When set to true, all operations include debugging info</description>
  <param-name>com.example.DEBUG_API_ENABLED</param-name>
  <param-value>true</param-value>
</context-param>

并在我的Application子类中:

@ApplicationPath("api")
public class RestApplication extends Application {
  @Context
  protected ServletContext sc;

  @Override
  public Set<Class<?>> getClasses() {
    Set<Class<?>> set = new HashSet<Class<?>>();
    boolean debugging = Boolean.parseBoolean(sc
            .getInitParameter("com.example.DEBUG_API_ENABLED"));

    if (debugging) {
        // enable debugging resources

答案 1 :(得分:1)

这在Jersey 2.5中得到修复:https://java.net/jira/browse/JERSEY-2184

您现在应该能够将@Context ServletContext注入Application构造函数。

以下是预期如何运作的示例:

public class MyApplication extends Application
{
  private final String myInitParameter;

  public MyApplication(@Context ServletContext servletContext)
  {
    this.myInitParameter = servletContext.getInitParameter("myInitParameter");
  }
}

您还可以调用ServiceLocator.getService(ServletContext.class)从应用中的任意位置获取ServletContext

答案 2 :(得分:0)

在Jersey 1中,可以将@Context ServletContext servletContext传递给Application类的构造函数,但在Jersey 2中这不再有效。看来泽西2队只会在请求时间注射。

要在Jersey 2中解决此问题,请使用匿名ContainerRequestFilter在请求时获取对ServletContext的访问权限,并将所需的init参数传递到Application类。

public class MyApplication extends Application {
  @Context protected ServletContext servletContext;
  private String myInitParameter;

  @Override
  public Set<Object> getSingletons() {
    Set<Object> singletons = new HashSet<Object>();
    singletons.add(new ContainerRequestFilter() {
      @Override
      public void filter(ContainerRequestContext containerRequestContext) throws IOException {
        synchronized(MyApplication.this) {
          if(myInitParameter == null) {
            myInitParameter = servletContext.getInitParameter("myInitParameter");
            // do any initialisation based on init params here
          }
        }
      }
      return singletons;
    });
  };
}
相关问题