Time for action – updating the view using AJAX
Let us create a Login Form with user name and password. When form is submitted, show the login status using AJAX. Perform the following steps for the same:
- Create a
login.xhtml
page with login form as follows:<h:form id="loginForm"> <p:panel header="Login Form" style="width: 500px;"> <h:panelGrid columns="2"> <p:outputLabel value="UserName"/> <p:inputText value="#{userController.loginUser.userName}"/> <p:outputLabel value="Password"/> <p:password value="#{userController.loginUser.password}"/> <p:commandButton action="#{userController.login}" value="Login" update="loginStatusMsg"/> <p:commandButton type="reset" value="Reset"/> <p:outputLabel value="#{userController.loginStatus}" id="loginStatusMsg"/> </h:panelGrid> </p:panel> </h:form>
- Create a
UserController.java
managed bean as follows:@ManagedBean @RequestScoped public class UserController { private User loginUser; private String loginStatus; public UserController() { this.loginUser = new User(); } public User getLoginUser() { return loginUser; } public void setLoginUser(User loginUser) { this.loginUser = loginUser; } public String getLoginStatus() { return loginStatus; } public void setLoginStatus(String loginStatus) { this.loginStatus = loginStatus; } public String login() { boolean validCredentials = "admin".equals(loginUser.getUserName()) && "admin".equals(loginUser.getPassword()); this.loginStatus = validCredentials? "Login Successful" : "Login failed"; return null; } }
- Point the browser to
http://localhost:8080/chapter01/login.jsf
.
When you enter UserName and Password and click on the Login button, the login status should be displayed using AJAX. Have a look at the following screenshot:
What just happened?
We have created a
Login Form with UserName and Password fields. When we submit the form, the model gets updated and login status will be set based on the provided credentials. As we have specified to update the view component with the ID loginStatusMsg
through update="loginStatusMsg"
, when you click on the Login button, the login status will be displayed without complete page refresh.