2012-06-04 46 views
0

我在websphere應用程序服務器8上使用jsf 2.0。RequestFilter和SessionBean授權

我有一個請求過濾器來授權用戶。用戶使用WebSEAL進行身份驗證。 userrole保存在MySQL DB中。 我的Requestfilter從每個請求的httpServletRequest獲取用戶主體。 然後我看看用戶擁有哪個角色(在數據庫中)。

這是非常差的,因爲我對每個請求DB查詢。

爲了改善這一點,我想實現的SessionBean其中包含的用戶名和角色。 我的問題是,我無法從我的requestfilter獲取sessionbean。 我試過在sessionclass中使用sessionbean作爲managingproperty。

但我總是得到一個NullPointerException,因爲SessionBean的是前所未有的調用。

那麼我該如何做到這一點?這是一個錯誤的方式?

回答

1

JSF存儲@SessionScoped @ManagedBean S作爲HttpSession的屬性。因此,Filter裏面有如下幾點可供選擇:

HttpSession session = ((HttpServletRequest) request).getSession(); 
SessionBean sessionBean = (SessionBean) session.getAttribute("sessionBean"); 

但是,您需要考慮到,這種方法不會自動創建時,它不會在範圍中不存在尚未豆。在全新的HTTP會話中第一次調用過濾器時就是這種情況。 Filtler即在之前FacesServlet之前被調用。然後您需要自己創建會話bean

HttpSession session = ((HttpServletRequest) request).getSession(); 
SessionBean sessionBean = (SessionBean) session.getAttribute("sessionBean"); 

if (sessionBean == null) { 
    sessionBean = new SessionBean(); 
    session.setAttribute("sessionBean", sessionBean); 
} 

// ... 

sessionBean.setRole(role); 

// ... 

JSF將無法與新的實例覆蓋它時,它已經會話範圍存在,但只是重複使用同樣的實例作爲Filter創建。

+0

我會嘗試。謝謝 – veote

0

見我類似answer,你應該能夠獲得您的SessionBean這樣

編輯

或者你可以嘗試這個方法

HttpSession session = (req (HttpServletRequest)).getSession(); 
MyManagedBean myManagedBean = session.getAttribute("myManagedBean");` 

或者你可以使用替代的PhaseListener你的過濾器。看到這個不錯的article關於使用PhaseListener來保護你的應用程序。

+0

現在我來到這裏的NullPointerException異常:會話=(HttpSession中)context.getExternalContext()的getSession(真); – veote

+0

不,您將在過濾器中獲取SessionBean(保存在會話中),然後通常可以調用像使用ManagedProperty注入的方法。 –

+0

我的會話中沒有SessionBean。這次會議的構造函數永遠不會被調用...... – veote