2

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!

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
Michael Bar-Sinai
  • 2,677
  • 18
  • 24

1 Answers1

1

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.

See also:

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452