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?
How to get the object of ServletContext interface. getServletContext() method of ServletConfig interface returns the object of ServletContext. getServletContext() method of GenericServlet class returns the object of ServletContext.
The JAX-RS @Context annotation allows to inject context related information into a class field, bean property or method parameter.
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
As others have noted, the servletContext can be injected at the field level. It can also be injected at the method level:
public static class MyService { private ServletContext context; private int minFoo; public MyService() { System.out.println("Constructor " + context); // null here } @Context public void setServletContext(ServletContext context) { System.out.println("servlet context set here"); this.context = context; minFoo = Integer.parseInt(servletContext.getInitParameter("minFoo")).intValue(); } @GET @Path("/thing") public void foo() { System.out.println("in wizard service " + context); // available here System.out.println("minFoo " + minFoo); } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With