2011-02-18 34 views
4

我想弄清楚如何使用JSF和支持託管bean調用f:ajax來註銷用戶。我遇到的問題是我無法弄清楚爲什麼Ajax偵聽器的調用順序和登錄表單的重新渲染。JSF阿賈克斯聽衆

下面是非常簡化的代碼。代碼的基本思想是這樣的

if (uid != null) { 
    // show log out 
} else { 
    // show log in 
} 

我顯然不理解有關ajax監聽器和窗體重新渲染是如何完成的。

JSF頁面

<html xmlns="http://www.w3.org/1999/xhtml" 
     xmlns:h="http://java.sun.com/jsf/html" 
     xmlns:f="http://java.sun.com/jsf/core" 
     xmlns:c="http://java.sun.com/jsp/jstl/core"> 
    <h:head> 
    <title>Facelet Title</title> 
    </h:head> 
    <h:body> 
    <f:view> 
     <h:form id="loginForm"> 
     <c:choose> 
      <c:when test="${userBean.uid != null}"> 
      <span>Hi, #{userBean.uid}</span> 
      <h:commandButton value="Logout"> 
       <f:ajax event="click" listener="#{userBean.logout}" render="loginForm"/> 
      </h:commandButton> 
      </c:when> 
      <c:otherwise> 
      <span>User name: </span> 
      <h:inputText value="#{userBean.uid}" id="uid" /> 
      <h:commandButton value="Login" action="#{userBean.login}" /> 
      </c:otherwise> 
      </c:choose> 
     </h:form> 
     </f:view> 
    </h:body> 
</html> 

package test.auth; 

import java.io.Serializable; 
import javax.inject.Named; 
import javax.enterprise.context.SessionScoped; 
import javax.faces.event.AjaxBehaviorEvent; 

@Named(value="userBean") 
@SessionScoped 
public class UserBean 
    implements Serializable 
{ 
    private static final long serialVersionUID = -4292770567982457272L; 

    private String uid; 
    /** Creates a new instance of UserBean */ 
    public UserBean() { 
    } 

    public String getUid() 
    { 
     return uid; 
    } 

    public void setUid(String uid) 
    { 
     this.uid = uid; 
    } 

    public String login() { 
     return "faces/index.xhtml"; 
    } 

    public void logout (AjaxBehaviorEvent event) { 
     this.uid = null; 
    } 
} 

與代碼的問題是,點擊logout形式重新加載時,但它仍然處於登錄狀態,即使盡管uid已被設置爲null。我已經用調試器檢查過了。那麼如何讓渲染在ajax監聽器之後執行?

回答

6

JSTL標籤是在視圖構建時執行的,而不是在視圖渲染時執行的。在JSF重新使用視圖狀態進行重新渲染時,JSTL標記將不會被重新執行,僅僅因爲它們不在那裏。

您想要使用JSF rendered屬性代替。

<h:form id="loginForm"> 
    <h:panelGroup rendered="#{userBean.uid != null}"> 
    <span>Hi, #{userBean.uid}</span> 
    <h:commandButton value="Logout"> 
     <f:ajax event="click" listener="#{userBean.logout}" render="loginForm"/> 
    </h:commandButton> 
    </h:panelGroup> 
    <h:panelGroup rendered="#{userBean.uid == null}"> 
    <span>User name: </span> 
    <h:inputText value="#{userBean.uid}" id="uid" /> 
    <h:commandButton value="Login" action="#{userBean.login}" /> 
    </h:panelGroup> 
</h:form> 
+0

非常棒,謝謝。 – 2011-02-18 14:50:59