JSF listener ajax

I am trying to figure out how to log out a user with f:ajax call using JSF and managed bean support. The problem I am facing is that I can’t understand why the call order for the Ajax listener and the registry of the login form.

Below is a very simplified code. The main idea of ​​the code is

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

I clearly don't understand something about how ajax listeners and rerender form are executed.

JSF Page

 <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> 

Bean

 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; } } 

The problem with the code is that when logout clicked, the form reloads, but it is still in the login state, even if the uid parameter is set to null . I checked this with a debugger. So, how do I make the render AFTER listening to ajax?

+4
source share
1 answer

JSTL tags are executed during the creation of watch time, and not during watch rendering. JSF is currently reusing view state for reprocessing, JSTL tags will not be re-executed, simply because they are no more.

Instead, you want to use the JSF rendered attribute.

 <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> 
+6
source

Source: https://habr.com/ru/post/1340301/


All Articles