Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rest easy and init params - how to access?

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!

like image 353
opensourcegeek Avatar asked Mar 25 '11 15:03

opensourcegeek


1 Answers

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();
}
like image 108
Mark Lutton Avatar answered Oct 22 '22 16:10

Mark Lutton