Get ServletContext in JAX-RS resource

TomcatServletsJakarta EeJax RsApplication Variables

Tomcat Problem Overview


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?

Tomcat Solutions


Solution 1 - Tomcat

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

Solution 2 - Tomcat

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.

Solution 3 - Tomcat

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:

<web-app>
  <!-- ... -->
  <listener>
    <listener-class>com.your.package.ServletContextClass</listener-class>
  </listener>

  <!-- Init parameters for db connection -->
  <context-param>
    <param-name>your_param</param-name>
    <param-value>your_param_value</param-value>
  </context-param>
  <!-- ... -->
</web-app>

Now create the servlet context class as follows.

public class ServletContextClass implements ServletContextListener
{
  public void contextInitialized(ServletContextEvent arg0) 
   {
    //use the ServletContextEvent argument to access the 
    //parameter from the context-param
    String my_param = arg0.getServletContext().getInitParameter("your_param");
   }//end contextInitialized method

  @Override
  public void contextDestroyed(ServletContextEvent arg0) 
  { }//end constextDestroyed method
}

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.

Solution 4 - Tomcat

Just use resource injection like this,

@Resource ServletContext servletContext;

Solution 5 - Tomcat

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleeeroyView Question on Stackoverflow
Solution 1 - TomcatAdeel AnsariView Answer on Stackoverflow
Solution 2 - TomcatJohnCView Answer on Stackoverflow
Solution 3 - TomcatKobby KanView Answer on Stackoverflow
Solution 4 - TomcatZZ CoderView Answer on Stackoverflow
Solution 5 - TomcatidbillView Answer on Stackoverflow