Rest easy and init params - how to access?

*爱你&永不变心* 提交于 2020-01-11 08:45:22

问题


I'd like to have some init params in my web.xml and retrieve them later in the application, I know I can do this when I have a normal servlet. However with resteasy I configure HttpServletDispatcher to be my default servlet so I'm not quite sure how I can access this from my rest resource. This might be completely simple or I might need to use a different approach, either way it would be good to know what you guys think. Following is my 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>

My question is how do I set something in the init-param and then retrieve it later in a restful resource. Any hints would be appreciated. Thanks guys!


回答1:


Use the @Context annotation to inject whatever you want into your method:

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

With @Context you can inject HttpHeaders, UriInfo, Request, HttpServletRequest, HttpServletResponse, ServletConvig, ServletContext, SecurityContext.

Or anything else if you use this code:

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();
}


来源:https://stackoverflow.com/questions/5434667/rest-easy-and-init-params-how-to-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!