Trong bài hôm nay , mình hướng dẩn các bạn để thiết lập 1 Bean trong java , thực ra trong bài trước chúng ta có đi qua Bean ( cơ bản ) .
Chúng ta chỉ cần biết đơn giản rằng .
Bean của chúng ta đơn thuần là 1 POJO , nó là 1 class java chuẩn gồm có các yêu cầu cơ bản sau :
- Một Constructor Empty.
- Một số properties cần thiết ( thường là private).
- Các setter/getter cho các attribute.
- Các method thể hiện như các action ( return String)
Từ 1 Bean trên chúng ta chia ra làm 3 phần trong managed Bean.
- Các method Setter/Getter đảm nhiệm cho việc Input/Output ( nó được gọi tự động , trước khi action conttroller method được gọi)
- Method thể hiện action ( action controller method ) . Thường thì mổi Bean chúng ta chỉ thiết lập một action controller để điều khiển việc chuyển page, tương tác với page ( thực tế chúng ta có thể tạo nhiều method hơn ) => Nó thực thi khi chúng ta nhân button submit form.
- Placeholders ( #{….} ) . đó là 1 loại kí hiệu có thể bạn sẻ gặp rất nhiều. Nó gọi từ method getter của chúng ta , được dùng để hiển thị kết quả (data) .
Example cho hôm nay : Thể hiện 1 form login , nếu login thành công hiển thị thông tin của tài khoản, thất bại sẻ hiển thị page Error cảnh báo lổi. Các bạn chúng tham khảo .
Toàn bộ cấu trúc thư mục project.
Class Account.java của chúng ta như sau :
package com.thaihoanghai.demo; public class Account { private String userName; private String password; private String birthDay; private String address; public Account() { } public Account(String userName, String password, String birthDay, String address) { super(); this.userName = userName; this.password = password; this.birthDay = birthDay; this.address = address; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public String getPasswordHide(){ return password.replaceAll(password.substring(3, password.length()), "*****"); } public void setPassword(String password) { this.password = password; } public String getBirthDay() { return birthDay; } public void setBirthDay(String birthDay) { this.birthDay = birthDay; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
Class Account này bản chất nó là Object để chúng ta thao tác, gồm các thông tin về 1 tài khoản.
Tiếp theo chúng ta tạo class LoginUtils.java ( Nó thể hiện các BussinessLogic cho chúng ta ).
package com.thaihoanghai.demo; import java.util.HashMap; import java.util.Map; public class LoginUtils { private static Map<String, Account> listAccount; public LoginUtils(){ listAccount = new HashMap<String, Account>(); Account a1 = new Account("kobee", "123456","10/10/1991","362/12/16 GV TN HCM"); Account a2 = new Account("jenny", "123456","18/05/1992","126 GV TN HCM"); Account a3 = new Account("ducky", "123456","29/02/1990","26/26/1 HBT HCM"); listAccount.put(a1.getUserName(), a1); listAccount.put(a2.getUserName(), a2); listAccount.put(a3.getUserName(), a3); } public static Map<String, Account> getListAccount() { return listAccount; } public Account getAccountWithIdAndPass(String userId, String password){ if(listAccount.containsKey(userId)){ Account account = listAccount.get(userId); if(account.getPassword().trim().equalsIgnoreCase(password.trim())){ return account; }else{ return null; } } return null; } }
Class LoginUtils này chứa 1 Account List , và một method thể hiện tác vụ , để check xem Account đó có tồn tại trong list của chúng ta hay không.
Tới bước này chúng ta đả thiết lập xong một nghiệp vụ login cơ bản.
Chúng ta tạo ra 1 LoginBean.java ( thể hiện nó là một ManagedBean) để tương tác với các page.xhtml (*.jsf)
package com.thaihoanghai.demo; import javax.faces.bean.ManagedBean; @ManagedBean public class LoginBean { private String userName; private String password; private Account account; private LoginUtils loginUtils = new LoginUtils(); public LoginBean() { } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Account getAccount() { return account; } // my action public String resultLogin(){ System.out.println("Into-1"); if(checkValue(userName) || checkValue(password)){ return "error"; }else if ((account = loginUtils.getAccountWithIdAndPass(userName, password)) != null){ return "success"; }else{ return "error"; } } private boolean checkValue(String value){ if(value.trim().equals("") || value.isEmpty()) return true; return false; } }
Trong class LoginBean chúng ta có một số thuộc tính như sau :
- 2 field Username, Password để tương tác với 2 textfield Username, password
- 1 Object Account dùng để tương tác với Ngiệp vụ của chúng ta, và củng để hiển thị data ( Khi login thành công)
- 1 LoginUtils thể hiện cho Businesslogic của chúng ta.
Note : Cách thức tương tác với Bean như sau
Ví dụ chúng ta có method getter như sau => tương ứng cách thao tác #{bean.attribute}
- setUserName/getUserName => #{loginBean.userName}
( viết thường chữ cái đầu tiên trong class ManagedBean, và viết thường chữ cái đầu tiên sau cụm từ set/get)
- Nếu chúng ta có 1 Object trong ManagedBean ( example Account), chúng ta có thể truy cập trực tiếp các attribute của Object
getAccount => #{loginBean.account.userName} or #{loginBean.account.address} , so on…
Ok chúng ta bắt đầu xây dựng các page XHTML (login, success, error ).
page login.xhtml như sau
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title>Example JSF - Login</title> </h:head> <h:body> <h:form> <fieldset> <legend>Login Example (Scope Request)</legend> <table width="400" border="1" cellspacing="2" cellpadding="2"> <tr> <td colspan="2" bgcolor="#66CCFF">Login</td> </tr> <tr> <td>UserName</td> <td><h:inputText value="#{loginBean.userName}"/></td> </tr> <tr> <td>Password</td> <td><h:inputSecret value="${loginBean.password}"/></td> </tr> <tr> <td></td> <td><h:commandButton value="Login" action="#{loginBean.resultLogin}"></h:commandButton></td> </tr> </table> </fieldset> </h:form> </h:body> </html>
Page login của chúng ta được hiển thị đầu tiên . chúng ta có 2 field username (h:inputText) , field password (h:inputSecret) thể hiện các value tương tứng với các method setter của chúng ta . (h:commandButton) là action đến method resultLogin trong Managed Bean của chúng ta
Page error.xhtml
[/code language="html"]
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”
xmlns:h=”http://java.sun.com/jsf/html”>
<h:head>
<title>Example JSF</title>
</h:head>
<h:body>
<h3>Not found UserName [#{loginBean.userName}] or Username and Password is invalid</h3>
</h:body>
</html>
[/code]
Nếu login không thành công chúng ta sẻ trả về page error tương ứng với method resultLogin return “error”, [#{loginBean.userName}] chúng ta lấy thông tin của username do người dùng input từ method getUserName trong bean.
Page success.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title>Example JSF</title> </h:head> <h:body> <h2>Login Successful</h2> Account Information<br/> <ul> <li>User Name: #{loginBean.account.userName} </li> <li>Password : #{loginBean.account.passwordHide} </li> <li>BirthDay : #{loginBean.account.birthDay} </li> <li>Address : #{loginBean.account.address} </li> </ul> </h:body> </html>
Khi login Success chúng ta sẻ hiện thị thông tin của Account khi chúng ta getAccount trong bean. và get các attributes trong Object đó
Hình ảnh show chương trình.
Chúc các bạn thành công !!!!
Leave a comment