I'm playing around with JAX-RS, deploying on Tomcat. It's basically:
@Path("/hello")
@Produces({"text/plain"})
public class Hellohandler {
@GET
public String hello() {
return "Hello World";
}
}
Is there any way I can get hold of the ServletContext
within my JAX-RS resource?
As others have noted, the servletContext can be injected at the field level. It can also be injected at the method level:
This will allow you to perform additional initialization with the servletContext available.
Obvious note - you don't have to use the method name setServletContext. You can use any method name you want so long as you follow the standard java bean naming pattern for setters, void setXXX(Foo foo) and use the @Context annotation.
Just use resource injection like this,
Check out: http://markmail.org/message/isy6mdpoh66vyi6k#query:jersey%20getservletcontext%20-spring+page:1+mid:sa7n465kfgdoskv5+state:results
The servlet context is also available when you implement the ServletContextListener. This makes it easy to load parameters such as connection string at start-up. You can define the listener class in web.xml that loads you ServletContextListener at startup of your web application.
Inside the web.xml file, add the
<listener>
and<context-param>
tags. The<listener>
specifies the class that is called at startup. The<context-param>
tag defines context parameter that is available within your web application.First, include the
<listener>
and<context-param>
tags in the web.xml file:Now create the servlet context class as follows.
You can now choose which static variable to assign the parameter you have read. This allows you to read the parameter once at start-up, and reuse many time through the static variable that you assign it to.
Furthermore,
@Resource
annotation might not work. Try thisThe injection doesn't happen until you hit the service method