【问题标题】:Get configuration data from web.xml when using a jersey ServletContainer使用 jersey ServletContainer 时从 web.xml 获取配置数据
【发布时间】:2013-06-23 19:53:10
【问题描述】:

我正在使用 jersey 在 Tomcat 中创建一个 webapp。我还没有创建 Servlet,我只是使用球衣 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>

我的 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>

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

这是一个示例资源类:

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

【问题讨论】:

    标签: java tomcat web-applications jersey


    【解决方案1】:

    您可以注入ServletContext 并从那里查找参数。比如:

    public class PingResource {
    
        @Context ServletContext context;
    
        public String myServiceMethod() {
           context.getInitParam("ContextParam");
        }
    
    }
    

    【讨论】:

    • 这看起来不错。但我假设它返回一个初始化参数。上下文参数呢?我看不到如何从 ServletContext 中获取它。
    • 哦,如果您不使用 Spring/Guice,我实际上不确定 @Resource 注入是否已在泽西岛完全实现。您应该可以改用@Context。示例已更新。
    • 对我来说它会要求创建@Context annotatron
    【解决方案2】:

    下面是对我有用的快照:)

    // 添加导入

    import javax.servlet.ServletContext;
    import javax.ws.rs.core.Context;
    

    //在你的类中添加属性

    @Context
    ServletContext context;
    

    // 在方法中使用上下文参数

    String companyName = this.context.getInitParameter("companyName");
    

    // 将上下文添加到 web.xml

    <context-param>
        <description>Context Parameter Test</description>
        <param-name>companyName</param-name>
        <param-value>Test Organization, Incorporated</param-value>
    </context-param>
    

    【讨论】:

      猜你喜欢
      • 2018-01-17
      • 2021-01-21
      • 2014-02-12
      • 2013-03-12
      • 1970-01-01
      • 2013-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多