2012-08-14 27 views
1

我知道如何申請對象在處理bean方法:在JSF2.x中,如何使用DI將請求對象傳遞給Managed Bean?

@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對象。

有沒有辦法使用DI和faces-config.xml傳遞請求?

Question number 9337433開始回答它,當你想傳遞請求對象上的東西。但是,我想要整個請求對象。

回答

1

FacesContext在EL範圍內可用#{facesContext}

所以,這應該做,只要託管bean本身也請求作用域。

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

然而,在你的JSF代碼javax.servlet進口量超過往往表明代碼味道和特定功能的要求也僅僅是解決了JSF方式。根據評論,您似乎有興趣收集請求Cookie。您應該使用ExternalContext類的非Servlet-API特定方法。有關完整的概述,請參閱javadoc。餅乾也可通過只是ExternalContext#getRequestCookieMap()

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

它也可通過#{cookie}在EL(也是在這裏,託管bean必須請求範圍):

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

或者,你可以看看JSF實用程序庫OmniFacesFaces類保存了一些常見的樣板。

String cookieValue = Faces.getRequestCookie("cookieName"); 
0

假設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指定。要將請求範圍的製品注入更廣的範圍,您必須使用level of indirection

相關問題