在JSF2.x中,如何使用DI将请求对象传递给托管Bean?
我知道如何在处理bean方法时请求对象:在JSF2.x中,如何使用DI将请求对象传递给托管Bean?,jsf,jsf-2,request,Jsf,Jsf 2,Request,我知道如何在处理bean方法时请求对象: @ManagedBean public class HomeAction { .... public String getHtmlFormattedCookiesInfo(){ FacesContext facesCtx = FacesContext.getCurrentInstance(); ExternalContext extCtx = facesCtx.getExternalCont
@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
....
}
}
}
但是,我不喜欢在我的bean对象中放入特定于Faces的代码
有没有办法使用DI和faces config.xml传递请求?
当您想要传递请求对象上的内容时,开始应答它。但是,我想要整个请求对象 假设bean是请求范围的,您可以使用托管属性注入另一个请求范围的值。例如:
@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
这也可以通过
faces config.xml
指定。要将请求范围内的工件注入到更广的范围内,您必须使用。假设bean是请求范围内的,您可以使用托管属性注入另一个请求范围内的值。例如:
@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
这也可以通过
faces config.xml
指定。要将请求范围内的人工制品注入到更广的范围内,您必须使用。可通过{FacesContext}
获得的FacesContext
在EL范围内
因此,只要托管bean本身也是请求作用域,就应该这样做
@ManagedProperty("#{facesContext.externalContext.request}")
private HttpServletRequest request;
然而,在JSF代码中导入
javax.servlet
更多地表明代码气味,并且特定的功能需求也可以通过JSF方式解决。根据评论,您似乎对收集请求cookie感兴趣。为此,您应该使用ExternalContext
类的非Servlet API特定方法。有关完整的概述,请参阅。Cookie也可通过以下方式获得:
或者,您可以查看JSF实用程序库的类来保存一些常见的样板文件
String cookieValue = Faces.getRequestCookie("cookieName");
FacesContext
在EL范围内,可通过{FacesContext}
获得
因此,只要托管bean本身也是请求作用域,就应该这样做
@ManagedProperty("#{facesContext.externalContext.request}")
private HttpServletRequest request;
然而,在JSF代码中导入
javax.servlet
更多地表明代码气味,并且特定的功能需求也可以通过JSF方式解决。根据评论,您似乎对收集请求cookie感兴趣。为此,您应该使用ExternalContext
类的非Servlet API特定方法。有关完整的概述,请参阅。Cookie也可通过以下方式获得:
或者,您可以查看JSF实用程序库的类来保存一些常见的样板文件
String cookieValue = Faces.getRequestCookie("cookieName");