0

I'm trying to read some parameters from my servlet init-params that reside on my web.xml, and make them accesible through variables in my program. I thought I could use the equivalent to the init() method of the HttpServlet.

There's a solution in this question : init method in jersey jax-rs web service.

I thought the first solution might work for me but the problem is that the ServletContextEvent only has access to the paramters defined in the context-param tags and I need them from my own servlet init-params values.

I wouldn't like to move the parameters from my servlet into the context-param tags because the parameters are really only relevant to that specific servlet.

Can someone point me in the right direction?

Community
  • 1
  • 1
J Paul
  • 17
  • 6

1 Answers1

1

With Jersey, all the init-params are available in a Configuration object that you can inject almost anywhere you want; resources, filters, etc.

@Path("test")
public class SomeResource {

    @Context
    private Configuration configuration;

    @GET
    public String get() {
        return (String) configuration.getProperty(InitParams.MY_INIT_PARAM);
    }
}

See Also:

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Is there some way I can get the InitParams at servlet startup? I'd like to read them just once and made them accesible through public variables. – J Paul May 10 '17 at 16:29
  • You can inject the Configuration in a ResourceConfig subclass constructor – Paul Samsotha May 10 '17 at 16:36
  • I'm getting WARNING: Unknown HK2 failure detected I already registered the class that extends ResourcecConfig as javax.ws.rs.Application in my web.xml. Don't know what could be the problem. Full log https://pastebin.com/RP31S36E – J Paul May 10 '17 at 16:53
  • Maybe it's not available yet. Not sure. You can try to use a `Feature` and get the configuration. Just use `featureContext.getConfiguration`. See [this post](http://stackoverflow.com/a/29275727/2587435) for a `Feature` example (you can just register it with the ResourceConfig.register). – Paul Samsotha May 10 '17 at 17:02
  • That seemed to work, although I still don't know what exactly is a Feature, I will research on that. Thanks. Also, unrelated, why did you quoted " make them accesible through variables" ? Did I phrased that wrong? Or is there a better way to do what I have in mind? – J Paul May 10 '17 at 17:30
  • I thought you wanted to inject values, somewhat like in Spring where you can inject `@Value("${some.prop}") String prop` anywhere. That's what the link examples. As far as a Feature, it's just a way to keep custom features modularized, e.g. you could register some services or filters that should be grouped together. Check [this out](https://psamsotha.github.io/jersey/2015/10/23/creating-reusable-jersey-extension.html) – Paul Samsotha May 10 '17 at 17:34