I have a piece of code that can be called both within and outside a HTTP request, but wants to access information in the HttpServletRequest if it is available. My first attempt was the following:
@Inject
private Instance<HttpServletRequest> httpReq;
void doSomethingIfInRequest(){
if (httpReq.isUnsatisfied()){
return;
}
httpReq.get()
// ...
}
However, even outside a request, isUnsatisfied()
returns false
, leading get()
to throw org.jboss.weld.exceptions.IllegalStateException: WELD-000710: Cannot inject HttpServletRequest outside of a Servlet request
.
I can solve this by catching the exception or creating another class that holds the request but was wondering whether CDI/Weld offers something to deal with this.