Jersey+Spring - Injecting servlet request

731 views Asked by At

I'm starting a Grizzly server as follows:

URI baseUri = UriBuilder.fromUri("http://localhost/").port(9998).build();

ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.packages("com.example");
resourceConfig.property("contextConfig", applicationContext);

HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, false);

server.start();

In the package com.example, I have filters as follows:

@Component
@Provider
@Priority(0)
public class MyFilter implements ContainerRequestFilter {

    @Context
    private HttpServletRequest httpServletRequest;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        /* httpServletRequest is null here */
    }
}

My filter is instantiated as expected by Spring. Also, JAX-RS detected it and uses the same instance instantiated by Spring. I'm trying to access the underlying HttpServletRequest but I can't find how.

I'm aware that the servlet request will never be injected until the filter instance is created as a proxy since the servlet request is request scoped. I tried to annotate the filter with @RequestScope, same thing.

1

There are 1 answers

10
Paul Samsotha On BEST ANSWER

You need to use the GrizzlyWebContainerFactory from

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-grizzly2-servlet</artifactId>
    <version>${jersey2.version}</version>
</dependency>

if you want to create servlet container. Currently, you are not creating a servlet container, that's why there is no HttpServletRequest available.

You can do something like

GrizzlyWebContainerFactory.create(baseUri, new ServletContainer(resourceConfig));