问题
Here is my code:
<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>
here is backing bean methods
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();
}
After login, logout button appears, but it works only on the second click. As you can see no ajax is used here, so this http://balusc.blogspot.com/2011/09/communication-in-jsf-20.html#AjaxRenderingOfContentWhichContainsAnotherForm can't help me.. How can I make it work correct? Thanks in advance.
回答1:
I think you have that problem because you need a redirection (using an outcome, not null) to a home page or something after logout. I had that problem, and I solved like this:
public String logout(){
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
if(session != null){
session.invalidate();
}
return "redirectToHomePageAfterLogout";
}
Hope this helps! :)
回答2:
This is because the Response URL for the form submit is the same as the Request that generated it. It gives the effect that the URL is always one behind where you actually are.
You can suffix your URLs with ?faces-redirect=true to force JSF to redirect you rather than forward you.
A better overview is given here
Your logOut action should return a String() which gives the name of the page to move to after the logOut function completes, however.
来源:https://stackoverflow.com/questions/11618450/hcommandbutton-works-from-the-second-click