Reputation: 2739
I have a managed bean (@Named
and @RequestScoped
), that is used by the rest of the application to retrieve the IP address of the client of the current request being handled. This bean is used from both JSF and JAX-RS contexts.
For JAX-RS, I inject the request to a field using
@Context
HttpServletRequest httpRequest;
If that's null
, I try to get the request like so:
final FacesContext jsfCtxt = FacesContext.getCurrentInstance();
if ( jsfCtxt != null ) {
return (HttpServletRequest) jsfCtxt.getExternalContext().getRequest();
} else {
Logger.getLogger(DataverseRequestServiceBean.class.getName()).log(Level.WARNING, "Cannot get the HTTP request object.");
return null;
}
However, some beans in the JSF context call this method before the context exists, and this jsfCtxt
is null
, and so no request is obtained. Which breaks things up.
Is there a one-way-catch-'em-all to get the HTTP request in Java EE from a managed bean?
Thanks!
Upvotes: 2
Views: 3482
Reputation: 1108782
The consistent Java EE way is CDI.
@Inject
private HttpServletRequest request;
Make sure you annotate your JAX-RS resources as @RequestScoped
to get it to work there as well.
Upvotes: 1