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!
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With