2011-06-17 91 views
1

我是JSF的新手,並使用JSF2來構建一個包含多個頁面的webapp。我使用會話作用域bean來保留通過不同頁面設置的一些參數。渲染前驗證頁面

當會話超時(或我重新部署應用程序)並轉到特定頁面時,此頁面無法正確呈現,因爲會話中缺少一些數據。此時我想要顯示主頁。

我想對所有頁面使用這種機制。所以一般來說,我想在渲染頁面之前進行一些驗證,並在驗證失敗時將用戶指向主頁。

我該如何處理?

+0

類似問題(和答案)[這裏](http://stackoverflow.com/q/1438351/620338) – 2011-06-17 10:23:38

+0

在我的使用情況下,會話超時,我意味着會話bean中的數據不再可用。這是我想通過將用戶引導到不同的頁面來回應的。當我得到一個ViewExpiredException時,我也有一個問題,但這是一個不同的問題。 – thehpi 2011-06-17 10:59:06

回答

4

在這種特殊情況下,我會使用一個簡單的filter,它鉤住JSF請求並檢查會話中託管bean的存在。下面的例子假設:

  • FacesServletweb.xml definied爲<servlet-name>facesServlet</servlet-name>
  • 你的會話範圍豆有yourSessionBean託管bean的名字。
  • 您的主頁位於home.xhtml

@WebFilter(servletName="facesServlet") 
public class FacesSessionFilter implements Filter { 

    @Override 
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 
     HttpServletRequest request = (HttpServletRequest) req; 
     HttpServletResponse response = (HttpServletResponse) res; 
     HttpSession session = request.getSession(false); 

     if (!request.getRequestURI().endsWith("/home.xhtml") && (session == null || session.getAttribute("yourSessionBean") == null)) { 
      response.sendRedirect(request.getContextPath() + "/home.xhtml"); // Redirect to home page. 
     } else { 
      chain.doFilter(req, res); // Bean is present in session, so just continue request. 
     } 
    } 

    // Add/generate init() and destroy() with empty bodies. 
} 

或者,如果你想這樣做更多的JSF十歲上下,加<f:event type="preRenderView">到主模板。

<f:metadata> 
    <f:event type="preRenderView" listener="#{someBean.preRenderView}" /> 
</f:metadata> 

@ManagedProperty(value="#{yourSessionBean}") 
private YourSessionBean yourSessionBean; 

public void preRenderView() { 
    if (yourSessionBean.isEmpty()) { 
     yourSessionBean.addPage("home"); 
     FacesContext.getCurrentInstance().getExternalContext().redirect("/home.xhtml"); 
    } 
}