if99.net

IF99 ITB

Archive for the ‘guice’ Category

? Deployment parameter for REST resource

without comments

When you are creating resource in a REST application, it will only be automatically created if you have an empty parameter. The problem is, sometime we need a resource that is configurable, so it can be reused by other applications.

We can solve this problem by defining init parameter in our web.xml like this:

<servlet>
    <servlet-name>JerseyTest</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param> 
        <param-name>param</param-name> 
        <param-value>test</param-value> 
    </init-param> 
</servlet>

Or if you’re using Guice (and jersey-guice), changing the end of your ServletModule like this:

serve("/*").with(GuiceContainer.class,
     ImmutableMap.of("param", "test"));

The parameter can be read by your resource by defining ServletConfig as field and annotate that with @Context. Example:

@Path("/test")
public class TestResource {
   @Context ServletConfig config;

   @GET public String testMethod() {
      return config.getInitParameter("param");
   }
}

Deployment parameter for REST resource originally appeared on firdau.si on January 28, 2011.

Written by nanda

January 28th, 2011 at 4:27 pm

Posted in guice,java,jersey,rest