使用jersey ServletContainer时从web.xml获取配置数据

tal*_*eth 8 java tomcat web-applications jersey

我正在使用泽西在Tomcat中创建一个webapp.我还没有创建一个Servlet,我只使用了jersey ServletContainer和一些Resource类.

我的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
    <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>
            com.sun.jersey.spi.container.servlet.ServletContainer
        </servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.mycompany.myproduct.rest</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>
Run Code Online (Sandbox Code Playgroud)

我的webapp需要读取一些配置值.我的印象是这样做的好方法是使用context-Params,如下所示:

<web-app>
   ...
  <context-param>
    <description>This is a context parameter example</description>
    <param-name>ContextParam</param-name>
    <param-value>ContextParam value</param-value>
  </context-param>
</web-app>
Run Code Online (Sandbox Code Playgroud)

这是最好的方法吗?如何从我的资源类中访问这些上下文参数?

这是一个示例资源类:

@Path("/api/ping")
public class PingResource {
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String helloWorld() {
        return "pong";
    }
}
Run Code Online (Sandbox Code Playgroud)

Jef*_*rey 10

您可以ServletContext从那里注入并查找参数.就像是:

public class PingResource {

    @Context ServletContext context;

    public String myServiceMethod() {
       context.getInitParam("ContextParam");
    }

}
Run Code Online (Sandbox Code Playgroud)