Search code examples
tomcatservletsjakarta-eejax-rsapplication-variables

Get ServletContext in JAX-RS resource


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?


Solution

  • 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