2011-03-25 19 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