Unable to find contextual data of type: javax.servlet.ServletContext

The combination of Spring Boot, RestEasy and Swagger 2 is not exactly a happy combination. Both Spring Boot and Swagger seems to prefer Jersey to RestEasy.  However, in my case as in others, RestEasy is mandated by factors outside my control.

Starting with Andy Wilkinson’s Spring Boot RestEasy (https://github.com/wilkinsona/spring-boot-resteasy), and then adding the latest Swagger 2 libraries (io.swagger), I was plagued by the error: Unable to find contextual data of type: javax.servlet.ServletContext

It seems the new io.swagger.jaxrs.listing.ApiListingResource causes RestEasy 3.0.9 to require a ThreadLocal reference to ServletContext which basically is not there, hence the error, which does not occur with the older com.wordnik.swagger.jaxrs.listing.ApiListingResource.

To get around this, I basically had to supply RestEasy with a thread local ServletContext myself, using a Jax-rs ContainerRequestFilter. The full project source is here: https://github.com/aosullivan/springboot-resteasy-swagger

The key Filter is as follows:

@ConditionalOnWebApplication
@Component
@Provider
@ServerInterceptor
public class ResteasyServletContext implements ContainerRequestFilter {

    @Inject 
    ServletContext sc;
    
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
		ResteasyProviderFactory.getContextDataMap().put(ServletContext.class, sc);
    }

}

Following this, everything seemed to work, and I could bring up swagger-ui and access the Jax-rs endpoints through it.

This condition is needed to support the spring SpringJUnit4ClassRunner, if you use that, or other contexts where the web container is not actually instantiated:

@ConditionalOnWebApplication

I get CORS issues when accessing swagger-ui from Chrome, which I can get around using the Chrome CORS plugin, https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en.  This didn’t happen under Jersey.

Advertisements

4 thoughts on “Unable to find contextual data of type: javax.servlet.ServletContext

  1. Hi Adrian,

    I was facing the same issue with RestEasy + Spring MVC and this post of yours saved a lot of time for me.

    Thanks a many.

    ~Irfan

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s