1

I know how to request object while processing a bean method:

@ManagedBean        
public class HomeAction {
    ....
    public String getHtmlFormattedCookiesInfo(){
        FacesContext facesCtx = FacesContext.getCurrentInstance();
        ExternalContext extCtx = facesCtx.getExternalContext();
        HttpServletRequest req = (HttpServletRequest) extCtx.getRequest();
        ....
        // now do something with the req object such as read cookie
        //    or pass req object to another another function 
        //    that knows nothing about JSF
        ....
        }
    }
}

But, I don't like putting Faces specific code in my bean object.

Is there a way to pass the request using DI and the faces-config.xml?

Question number 9337433 starts to answer it when you want to pass something that is on the request object. But, I want the entire request object.

Community
  • 1
  • 1
JeffJak
  • 2,008
  • 5
  • 28
  • 40

2 Answers2

1

The FacesContext is in EL scope available by #{facesContext}.

So, this should do, provided that the managed bean is itself also request scoped.

@ManagedProperty("#{facesContext.externalContext.request}")
private HttpServletRequest request;

However, having javax.servlet imports in your JSF code more than often indicate code smells and that the particular functional requirement can also just be solved the JSF way. As per the comments, you seem to be interested in collecting request cookies. You should be using the non-Servlet-API-specific methods of the ExternalContext class for this. See the javadoc for a complete overview. The cookies are also available by just ExternalContext#getRequestCookieMap():

Map<String, Object> cookies = externalContext.getRequestCookieMap();

Which is also available by #{cookie} in EL (also here, the managed bean must be request scoped):

@ManagedProperty("#{cookie.cookieName}")
private String cookieValue;

Alternatively, you could look at the Faces class of the JSF utility library OmniFaces to save some common boilerplate.

String cookieValue = Faces.getRequestCookie("cookieName");
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

Assuming the bean is request scoped, you can use a managed property to inject another request-scoped value. For example:

@ManagedBean
@RequestScoped
public class Alfa {
  @ManagedProperty("#{paramValues.foo}")
  private String[] foo;

  public String[] getFoo() {
    return foo;
  }

  public void setFoo(String[] foo) {
    this.foo = foo;
  }

// remainder elided

This can also be specified via faces-config.xml. To inject a request-scoped artefact into a broader scope, you will have to employ a level of indirection.

McDowell
  • 107,573
  • 31
  • 204
  • 267