Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 858
leeeroy Avatar asked Nov 29 '09 03:11

leeeroy


People also ask

Which is the correct way to get ServletContext object?

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.

What is context in Jax?

The JAX-RS @Context annotation allows to inject context related information into a class field, bean property or method parameter.


2 Answers

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 
like image 174
Adeel Ansari Avatar answered Sep 29 '22 16:09

Adeel Ansari


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.

like image 31
JohnC Avatar answered Sep 29 '22 16:09

JohnC