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 中设置一些东西,然后稍后在一个安静的资源中检索它。任何提示将不胜感激。多谢你们!

4

1 回答 1

22

使用 @Context 注释将您想要的任何内容注入到您的方法中:

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

使用@Context,您可以注入 HttpHeaders、UriInfo、Request、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();
}
于 2011-04-04T14:48:05.680 回答