![](/img/trans.png)
[英]Is it possible to catch ViewExpriedException in PhaseListener?
[英]handleNavigation not working in PhaseListener
我有一個PhaseListener來控制用戶對某些頁面的訪問,如果用戶未登錄,則將其重定向到loginpage。
問題是我的方法handleNavigation沒有重定向用戶。 它運行但不重定向用戶。
當用戶鍵入不應具有訪問權限的URL時,該方法將運行,但是該頁面將打開,而不會重定向到登錄頁面。
怎么了?
public class AuthorizationListener implements PhaseListener {
public void afterPhase(PhaseEvent event) {
FacesContext facesContext = event.getFacesContext();
String currentPage = facesContext.getViewRoot().getViewId();
boolean isLoginPage = (currentPage.lastIndexOf("login.xhtml") > -1);
if(isLoginPage)
return;
if(currentPage.indexOf("/rws/") != -1)
{
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
Object currentUser = session.getAttribute("usuario");
if (!isLoginPage && currentUser == null) {
NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
nh.handleNavigation(facesContext, null, "loginPage");
}
}
}
public void beforePhase(PhaseEvent event) {
System.out.println("Hellow World");
}
public PhaseId getPhaseId() {
return PhaseId.RENDER_RESPONSE;
}
}
我的面孔配置
<navigation-rule>
<from-view-id>/*</from-view-id>
<navigation-case>
<from-outcome>loginPage</from-outcome>
<to-view-id>/login.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
<lifecycle>
<phase-listener>br.com.testes.filter.AuthorizationListener</phase-listener>
</lifecycle>
您正在渲染響應的后階段執行代碼。 因此,在JSF渲染並完成響應之后。 到那時,整個HTTP響應已經完成,並已完全發送到Web瀏覽器。
這是無可挽回的一點。 您的代碼太遲了,無法更改響應。
而是在還原視圖階段進行監聽。 或者,最好使用servlet過濾器 。 JSF階段偵聽器是一項過於笨拙的工具(它不會在非JSF請求中啟動,並且在JSF請求期間最多觸發12次)。 servlet過濾器是完成此任務的正確工具。 您可以在此答案中找到一個具體示例: 使用登錄過濾器時缺少JSF頁面樣式 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.