在应用程序中获取 ServletContext

2022-01-21 00:00:00 java jax-rs jersey

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

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 the following snippet but it does not seem to work - the ctx is not set:

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;
    }
}

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>

问题是我需要从中获取上下文参数.如果有其他方法,如果有人提供提示,我将不胜感激.

The problem is that I need to get context parameters from it. If there is another way, I would be grateful if somebody gave a hint.

我了解 Context 注释可能不是为此目的.实际上,我不需要 ServletContext 本身.如果我能从 web.xml 中获取上下文参数,我会非常高兴.

I understand that Context annotation might not be purposed for this. Actually, I do not need ServletContext itself. If only I could get context params from web.xml, I would be absolutely happy.

这是我真正需要的示例:

Here is an example of what I really need:

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;
    }
}

谢谢.

推荐答案

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

Since Jersey 2.5, ServletContext can be injected directly in constructor: https://java.net/jira/browse/JERSEY-2184

public class MyApplication extends ResourceConfig {
    public MyApplication(@Context ServletContext servletContext) {
       // TODO
    }
}

相关文章