使用Jersey ServletContainer时从web.xml获取配置数据 [英] Get configuration data from web.xml when using a jersey ServletContainer
本文介绍了使用Jersey ServletContainer时从web.xml获取配置数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用jersey在Tomcat中创建一个Web应用程序.我还没有创建Servlet,我只是使用球衣ServletContainer和一些Resource类.
I'm creating a webapp in Tomcat using jersey. I haven't created a Servlet, I just use the jersey ServletContainer and some Resource classes.
我的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>
我的Web应用程序需要读取一些配置值.我的印象是,执行此操作的一个好方法是使用上下文参数,例如:
My webapp needs to read some configuration values. I have the impression that a good way to do this is with context-Params, like this:
<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>
这是最好的方法吗?如何从资源类访问这些上下文参数?
Is this the best way? How can I access these context params from my resource classes?
这是一个示例资源类:
@Path("/api/ping")
public class PingResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String helloWorld() {
return "pong";
}
}
推荐答案
您可以注入ServletContext
并从那里查找参数.像这样:
You can inject the ServletContext
and look up the parameters from there. Something like:
public class PingResource {
@Context ServletContext context;
public String myServiceMethod() {
context.getInitParam("ContextParam");
}
}
这篇关于使用Jersey ServletContainer时从web.xml获取配置数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文