2
votes

Toying around with Quarkus, I'm trying to get the ServletContext injected in my application:

@Controller
@Path("/greeting/")
@RequestScoped
public class GreetingResource {
    @Inject
    ServletContext servletContext;
}

It compiles just fine, but in the packaging phase the quarkus-maven-plugin fails with:

[1] Unsatisfied dependency for type javax.servlet.ServletContext and qualifiers [@Default]
    - java member: exampleapp.GreetingResource#servletContext
    - declared on CLASS bean [types=[java.lang.Object, exampleapp.GreetingResource], qualifiers=[@Default, @Any], target=exampleapp.GreetingResource]

My app has a dependency on io.quarkus:quarkus-resteasy, which pulls in io.quarkus:quarkus-undertow, which in turn pulls in io.undertow:undertow-servlet.

I'd expect any of the Undertow-extensions to provide the injection of the ServletContext, but apparently my assumption is wrong... Any ideas?

2

2 Answers

3
votes

@Inject ServletContext works on Java EE Environment only. Quarkus integrates JAX-RS so you can access the ServletContext instance by using JAX-RS @Context

@Controller
@Path("/greeting/")
@RequestScoped
public class GreetingResource {

    // javax.ws.rs.core.Context
    @Context
    ServletContext servletContext;

    // OR

    @GET
    @Path("/test")
    @Produces({ MediaType.TEXT_PLAIN })
    public Response test(@Context ServletContext servletContext) {
        // return ...
    }
}

Your way also works but it depends explicitly on Undertow API.

UPDATE:

Quarkus version 0.17.0+ added support of ServletContext injection using CDI @Inject annotation. See this https://github.com/quarkusio/quarkus/pull/2850

0
votes

A bit of fiddling around showed me that there's no producer method for this type... The following snippet helped me out:

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Singleton;
import javax.servlet.ServletContext;

import io.undertow.servlet.handlers.ServletRequestContext;

@Singleton
public class ServletContextProducer {
    @Produces
    @RequestScoped
    public ServletContext servletContext() {
        return ServletRequestContext.current().getCurrentServletContext();
    }
}