H: commandButton works from the second click

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> 

bean methods supported here

  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 entering the system, the exit button will appear, but it only works with the second click. Since you cannot see that ajax is not used here, so http://balusc.blogspot.com/2011/09/communication-in-jsf-20.html#AjaxRenderingOfContentWhichContainsAnotherForm cannot help me .. How can I get it to work right? Thanks in advance.

+1
source share
2 answers

I think you have this problem because you need to redirect (using the result, not null) to the home page or something after logging out. I had this problem and solved it like this:

 public String logout(){ HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false); if(session != null){ session.invalidate(); } return "redirectToHomePageAfterLogout"; } 

Hope this helps! :)

+4
source

This is because the response URL for submitting the form is the same as the request that generated it. This causes the url to always be behind where you really are.

You can suffix your URLs with: faces-redirect = true to force JSF to redirect you rather than forward you.

Below is the best review here

Your logOut action should return String (), which gives the name of the page to move after the logOut function completes.

0
source

All Articles