5

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

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

4

3 回答 3

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
于 2013-10-25T23:58:46.057 回答
3

这已在 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从应用程序中的任何点获取 。

于 2013-11-15T13:10:06.703 回答
0

在 Jersey 1 中可以传递@Context ServletContext servletContextApplication类的构造函数,但在 Jersey 2 中这不再有效。似乎 Jersey 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;
    });
  };
}
于 2013-11-14T12:30:29.343 回答