我正在使用 jersey 在 Tomcat 中创建一个网络应用程序。我没有创建 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>
我的 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";
}
}
最佳答案
您可以注入(inject) ServletContext
并从那里查找参数。像这样的东西:
public class PingResource {
@Context ServletContext context;
public String myServiceMethod() {
context.getInitParam("ContextParam");
}
}
关于java - 使用 Jersey ServletContainer 时从 web.xml 获取配置数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17324075/