2011-03-25 17 views
6

我想在我的web.xml中有一些初始化参数,稍后在应用程序中检索它们,我知道当我有一个普通的servlet时可以做到这一点。然而,由于resteasy,我将HttpServletDispatcher配置为我的默认servlet,所以我不太确定如何从我的其余资源访问它。这可能是非常简单的,或者我可能需要使用不同的方法,无论哪种方式,知道你们的想法是很好的。以下是我的web.xml,轻松休息并初始化参数 - 如何访问?

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> 
<display-name>RestEasy sample Web Application</display-name> 
<!-- <context-param> 
     <param-name>resteasy.scan</param-name> 
     <param-value>true</param-value> 
</context-param> --> 

<listener> 
    <listener-class> 
     org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap 
    </listener-class> 
</listener> 

<servlet> 
    <servlet-name>Resteasy</servlet-name> 
    <servlet-class> 
     org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher 
    </servlet-class> 
    <init-param> 
     <param-name>javax.ws.rs.Application</param-name> 
     <param-value>com.pravin.sample.YoWorldApplication</param-value> 
    </init-param> 
</servlet> 

<servlet-mapping> 
    <servlet-name>Resteasy</servlet-name> 
    <url-pattern>/*</url-pattern> 
</servlet-mapping> 

</web-app> 

我的问题是如何设置在init-PARAM东西,然后在一个宁静的资源以后检索。任何提示将不胜感激。多谢你们!

+0

只是为了使问题更清楚,如果我有多个宁静的资源,我想能够设置初始化-PARAMS为他们每个人,并在以后检索在该资源内部。如果有更好的方法,我会同样高兴......所以任何人? – opensourcegeek 2011-03-29 07:14:01

回答

21

使用@Context注释注入任何你想进入你的方法:

@GET 
public Response getWhatever(@Context ServletContext servletContext) { 
    String myParm = servletContext.getInitParameter("parmName"); 
} 

随着@Context你可以注入HttpHeaders,UriInfo,请求,的HttpServletRequest,HttpServletResponse的,ServletConvig,ServletContext中,SecurityContext的。

或其他任何东西,如果你使用此代码:

public class MyApplication extends Application { 
    public MyApplication(@Context Dispatcher dispatcher) { 
    MyClass myInstance = new MyClass(); 
    dispatcher.getDefautlContextObjects(). 
     put(MyClass.class, myInstance); 
    } 
} 

@GET 
public Response getWhatever(@Context MyClass myInstance) { 
    myInstance.doWhatever(); 
} 
+0

我明白你的意思,如果你可以通过web.xml而不是代码完成这项工作,你会很棒 - 但是谢谢你的回应! – opensourcegeek 2011-04-05 08:26:29

+0

很好的答案,@pravin你应该接受这个答案,如果它帮助你。 – gresdiplitude 2012-12-03 10:40:29

+0

谢谢忘了这么做! - 由于各种原因,我确实从atex cxf转移到了apache cxf,不过这是正确的答案。 – opensourcegeek 2012-12-03 11:18:24