Get ServletContext in JAX-RS resource

leeeroy picture leeeroy · Nov 29, 2009 · Viewed 54.4k times · Source

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?

Answer

Adeel Ansari picture Adeel Ansari · Nov 29, 2009

Furthermore, @Resource annotation might not work. Try this

@javax.ws.rs.core.Context 
ServletContext context;

The injection doesn't happen until you hit the service method

public class MyService {
    @Context ServletContext context;

    public MyService() {
         print("Constructor " + context);  // null here     
    }

    @GET
    @Path("/thing") {               
             print("in  wizard service " + context); // available here