SSH架構之Struts(4)——Struts查漏補缺BeanUtils的簡單使用,sshbeanutils
一)、背景
上篇部落格我們提到了一個重要的操作javaBean工具——BeanUtils。這篇部落格我們簡單來瞭解一下BeanUtils的相關知識。BeanUtils作為一個第三方的服務,提供了對javaBean的各種操作服務。
其主要的功能總結如下:
1、通過BeanUtils.cloneBean()方法複製一個JavaBean的執行個體
2、通過BeanUtils.copyProperties()在JaveBean之間實現屬性的複製
3、通過BeanUtils.setProperty()為一個JavaBean的執行個體設定屬性
4、通過BeanUtils.getProperty從JavaBean的執行個體中讀取相關的資訊
二)具體實踐:
public class User {private String userNameString;private String userPasswordString;public String getUserNameString() {return userNameString;}public void setUserNameString(String userNameString) {this.userNameString = userNameString;}public String getUserPasswordString() {return userPasswordString;}public void setUserPasswordString(String userPasswordString) {this.userPasswordString = userPasswordString;}}
1)複製實體
User nUser=new User();User suser=(User)BeanUtils.cloneBean(nUser);
有興趣的可以研究一下suser和nuser是不是同一個執行個體?也就是說BeanUtils複製出來的是不是指向的同一個執行個體?
2)屬性複製
具有相同屬性的JavaBean,通過BeanUtils,可以實現屬性的複製。常見的情況就是Struts1中,實體物件擷取ActionForm中的值。
傳統的方法:
// 擷取 ActionForm 表單資料UserActionForm uForm = (UserActionForm) form;User user = new User();// 逐一賦值user.setUsername(uForm.getUsername);user.setPassword(uForm.getPassword);user.setAge(uForm.getAge);
屬性少,逐一賦值無可厚非。但是如果屬性多點的話,那麼多的屬性一條一條賦值起來可是一件麻煩的事情.
使用BeanUtils後
// 採用BeanUtils後UserActionForm uForm = (UserActionForm) form;User user = new User();// 屬性copy賦值BeanUtils.copyProperties(user, uForm);
一句簡單的BeanUtils.copyProperties(user, uForm);就將UForm所有的屬性值賦值給了user。
3)、Get和SetProperty
通過get和set動態給實體屬性實現賦值。
//給對象的某個屬性賦值BeanUtils.setProperty(nUser, "UserNameString","leilei");//擷取某個對象的屬性值BeanUtils.getProperty(nUser,"UserNameString");其中BeanUtils會使用ConvertUtils類把字串轉為Bean屬性的真正類型,方便從HttpServletRequest等對象中提取bean,或者把bean輸出到頁面。而PropertyUtils就會原色的保留Bean原來的類型。
三)、小結
BeanUtils作為一個第三方的提供操作JavaBean方法的服務,在struts1中,使用BeanUtils實現了實現屬性值的轉換和賦值。 (BeanUtils.populate(bean, properties)); 而這裡主要擴充下BeanUtils的其他用途和優點。