Today I Learned

Stuff I wish someone else had written down.

Current Servlet Request in a CDI Bean

How to inject the current request into a @RequestScoped CDI bean:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import javax.inject.Provider;

@RequestScoped
class Foo {

    private final Provider<HttpServletRequest> currentRequestProvider;
    
    @Inject
    public Foo(Provider<HttpServletRequest> currentRequestProvider) {
        this.currentRequestProvider = currentRequestProvider;
    }
    
    @PostConstruct
    public void postConstruct() {
        currentRequestProvider.get().getRequestURL()
    }
}

You must wrap the request in a Provider or else the application server will complain that there does not (yet) exist a bean of that type.

TAGS