这是我的代码:
<h:form>
<h:messages errorClass="errorMessage" infoClass="infoMessage"
warnClass="warnMessage"></h:messages>
<h:panelGroup id="login" layout="block" rendered="#{!securityBean.authorized}">
<h:outputText value="login:"/>
<h:inputText id="username" value="#{securityBean.username}"/>
<h:outputText value="password:"/>
<h:inputSecret id="password" value="#{securityBean.password}"/>
<h:commandButton value="login" action="#{securityBean.login}"/>
</h:panelGroup>
<h:panelGroup id="logout" layout="block" rendered="#{securityBean.authorized}">
<h:graphicImage id="img" library="img" name="login_success.jpg"/>
<h:commandButton value="logout" action="#{securityBean.logout}"/>
</h:panelGroup>
</h:form>
这是支持bean的方法
public Object login() throws ServletException {
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
try {
request.login(username, password);
} catch (ServletException e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "An Error Occured: Login failed", null));
e.printStackTrace();
}
return null;
}
public Object logout(){
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
if(session != null){
session.invalidate();
}
return null;
}
public boolean isAuthorized() {
return FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal() != null &&
FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName() != null &&
!FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName().isEmpty();
}
登录后,会出现注销按钮,但仅在第二次单击时有效。正如你所看到的,这里没有使用 ajax,所以这个http://balusc.blogspot.com/2011/09/communication-in-jsf-20.html#AjaxRenderingOfContentWhichContainsAnotherForm帮不了我。我怎样才能让它工作正确的?提前致谢。