【发布时间】:2013-10-25 18:01:44
【问题描述】:
我的 Web 容器知道我的应用程序是在调试模式还是在发布模式下运行。我想将此信息传递给我的 ResourceConfig/Application 类,但不清楚如何将这些信息读回。
是否可以通过 servlet/filter 参数传递信息?如果有,怎么做?
【问题讨论】:
标签: jersey jax-rs jersey-2.0
我的 Web 容器知道我的应用程序是在调试模式还是在发布模式下运行。我想将此信息传递给我的 ResourceConfig/Application 类,但不清楚如何将这些信息读回。
是否可以通过 servlet/filter 参数传递信息?如果有,怎么做?
【问题讨论】:
标签: jersey jax-rs jersey-2.0
这是我的做法:
在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
【讨论】:
getSingletons 返回我的 @Provider 类)。
这在 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。
【讨论】:
在 Jersey 1 中,可以将 @Context ServletContext servletContext 传递给 Application 类的构造函数,但在 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;
});
};
}
【讨论】: