BeanUtils

今日學習目標 :

  1. 可以說出BeanUtils的做用
  2. 可以使用BeanUtils封裝數據
  3. 可以編寫XML綜合案例

 

 

  1. BeanUtils (*****瞭解*****)

JavaBean 介紹 :java

       JavaBean 它是一個簡單的Java類, 這個類擁有 get 和 set 方法便可. 但要求這個類必須有一個公開的空參構造方法.apache

       後期開發中, 這個類通常會保存在名爲 domain 或者 beans 包中.dom

 

 

BeanUtils 介紹 :ide

       在 Servlet 中通常須要獲取頁面提交的form表單中的數據, 而後封裝到一個JavaBean上.工具

       這樣咱們須要書寫大量的 getParameter 獲取提交的參數, 同時還要使用 JavaBean 的 setParameter 方法把數據所有封裝到對象上.學習

       因而 Apache 公司給咱們提供了能夠快速獲取頁面數據, 並將數據封裝到JavaBean對象上的方式.this

 

       BeanUtils 類的功能是把一個Map集合中的數據, 封裝到一個 JavaBean 上. 使用BeanUtils工具類中的populate方法就能夠把Map集合中的數據封裝到指定的bean上.Map中的key名稱必須和bean對象的屬性名稱保持一致.spa

 

Request 請求 -> getParameter -> getParameterMap(); -> populate 填充 -> JavaBean 類的對象..net

 

 

 

BeanUtils 做用 :orm

       能夠爲JavaBean的屬性設置值, 獲取值, 並經過Map爲JavaBean的數值賦值.

 

 

連接 : http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgi

 

連接 : http://commons.apache.org/proper/commons-logging/download_logging.cgi

 

 

BeanUtils 是 Apache commons組件的成員之一,主要用於簡化JavaBean封裝數據的操做。它能夠給JavaBean封裝一個字符串數據,也能夠將一個表單提交的全部數據封裝到JavaBean中。

       使用第三方工具,須要導入jar包:

             

      

 

方法

描述

BeanUtils對象

populate(Object bean,

Map<String,String[]> properties)  

將Map數據封裝到指定Javabean中,通常用於將表單的全部數據封裝到javabean

setProperty(Object obj,String name,Object value)

設置屬性值

getProperty(Object obj,String name)

得到屬性值

 

  1. 提供JavaBean User ,並提供對應的構造方法

 

  1. package cn.itcast.domain;
  2.  
  3. public class User {
  4.        // 屬性
  5.        private String id;
  6.        private String username;
  7.        private String pwd;
  8.        private int age;
  9.        private float scores;
  10.  
  11.        public User(String id, String username, String pwd, int age, float scores) {
  12.               super();
  13.               this.id = id;
  14.               this.username = username;
  15.               this.pwd = pwd;
  16.               this.age = age;
  17.               this.scores = scores;
  18.        }
  19.  
  20.        public User() {
  21.               super();
  22.        }
  23.       
  24.        @Override
  25.        public String toString() {
  26.               return "User [id=" + id + ", username=" + username + ", pwd=" + pwd + ", age=" + age + ", scores=" + scores
  27.                            + "]";
  28.        }
  29.        public int getAge() {
  30.               return age;
  31.        }
  32.        public float getScores() {
  33.               return scores;
  34.        }
  35.        public void setAge(int age) {
  36.               this.age = age;
  37.        }
  38.        public void setScores(float scores) {
  39.               this.scores = scores;
  40.        }
  41.        public String getId() {
  42.               return id;
  43.        }
  44.        public String getUsername() {
  45.               return username;
  46.        }
  47.        public String getPwd() {
  48.               return pwd;
  49.        }
  50.        public void setId(String id) {
  51.               this.id = id;
  52.        }
  53.        public void setUsername(String username) {
  54.               this.username = username;
  55.        }
  56.        public void setPwd(String pwd) {
  57.               this.pwd = pwd;
  58.        }
  59. }

 

 

  1. 功能1:設置屬性
  2. 功能2:得到屬性

 

  1. import org.apache.commons.beanutils.BeanUtils;
  2. import org.junit.Test;
  3.  
  4. public class BeanUtilsDemo01 {
  5.        @Test
  6.        public void demo01() throws Exception {
  7.               User user = new User();
  8.              
  9.               // 設置
  10.               BeanUtils.setProperty(user, "id", "u001");
  11.               BeanUtils.setProperty(user, "username", "Jack");
  12.               BeanUtils.setProperty(user, "pwd", "123456");
  13.               BeanUtils.setProperty(user, "age", 18);
  14.               BeanUtils.setProperty(user, "scores", 99.5f);
  15.              
  16.               System.out.println(user);
  17.        }
  18.       
  19.        @Test
  20.        public void demo02() throws Exception {
  21.               User user = new User("u001", "Jack", "123456", 18, 99.5f);
  22.              
  23.               String id = BeanUtils.getProperty(user, "id");
  24.               String username = BeanUtils.getProperty(user, "username");
  25.               String pwd = BeanUtils.getProperty(user, "pwd");
  26.               String age = BeanUtils.getProperty(user, "age");
  27.               String scores = BeanUtils.getProperty(user, "scores");
  28.              
  29.               System.out.println(id + ", " + username + ", " + pwd + ", " + age + ", " + scores);
  30.        }
  31. }

 

 

  1. 功能3:封裝表單數據,使用Map 模擬 request.getParameterMap()

  1. import java.util.HashMap;
  2. import java.util.Map;
  3.  
  4. import org.apache.commons.beanutils.BeanUtils;
  5.  
  6. public class BeanUtilsDemo02 {
  7.        public static void main(String[] args) throws Exception {
  8.              
  9.               // 功能3 : 封裝表單數據, 使用 Map 模擬 request.getParameterMap();
  10.               // 需求 : 將數據封裝到 JavaBean 對象中
  11.               User user = new User();
  12.               BeanUtils.populate(user, Request.getParameterMap());
  13.               System.out.println(user);
  14.        }
  15. }
  16.  
  17. class Request {
  18.        // 方法
  19.        public static Map<String, Object> getParameterMap() {
  20.               HashMap<String, Object> map = new HashMap<String, Object>();
  21.               map.put("id", "u001");
  22.               map.put("username", "Jack");
  23.               map.put("pwd", "123456");
  24.               map.put("age", 18);
  25.               map.put("scores", 99.5f);
  26.               return map;
  27.        }
  28. }

 

 

 

 

  1. 綜合案例1 (*****練習*****)

  讀取XML中的配置文件信息,使用BeanUtils工具類建立JavaBean對象,將XML中的數據保存到JavaBean類的屬性中.

 

 

xml文件 :

 

<?xml version="1.0" encoding="UTF-8"?>

<beans>

    <bean className="cn.itcast.bean.Employee">

       <property name="id" value="1"></property>

       <property name="name" value="張三"></property>

       <property name="salary" value="20000.00"></property>

    </bean>

    <bean className="cn.itcast.bean.Student">

       <property name="name" value="翠花"></property>

       <property name="age" value="18"></property>

       <property name="gender" value=""></property>

       <property name="score" value="99.5f"></property>

    </bean>

</beans>

 

 

建立兩個 JavaBean 類 :

 

  1. package cn.itcast.domain;
  2.  
  3. public class Employee {
  4.        // 屬性
  5.        private int id;
  6.        private String name;
  7.        private double salary;
  8.       
  9.        // 構造方法重載
  10.        public Employee(int id, String name, double salary) {
  11.               super();
  12.               this.id = id;
  13.               this.name = name;
  14.               this.salary = salary;
  15.        }
  16.       
  17.        @Override
  18.        public String toString() {
  19.               return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]";
  20.        }
  21.  
  22.        // setter & getter
  23.        public Employee() {
  24.               super();
  25.        }
  26.        public int getId() {
  27.               return id;
  28.        }
  29.        public String getName() {
  30.               return name;
  31.        }
  32.  
  33.        public double getSalary() {
  34.               return salary;
  35.        }
  36.       
  37.        public void setId(int id) {
  38.               this.id = id;
  39.        }
  40.        public void setName(String name) {
  41.               this.name = name;
  42.        }
  43.        public void setSalary(double salary) {
  44.               this.salary = salary;
  45.        }
  46. }

 

 

  1. package cn.itcast.domain;
  2.  
  3. public class Student {
  4.        // 屬性
  5.        private String name;
  6.        private int age;
  7.        private char gender;
  8.        private float score;
  9.        public Student(String name, int age, char gender, float score) {
  10.               super();
  11.               this.name = name;
  12.               this.age = age;
  13.               this.gender = gender;
  14.               this.score = score;
  15.        }
  16.        public Student() {
  17.               super();
  18.        }
  19.        @Override
  20.        public String toString() {
  21.               return "Student [name=" + name + ", age=" + age + ", gender=" + gender + ", score=" + score + "]";
  22.        }
  23.        public String getName() {
  24.               return name;
  25.        }
  26.        public int getAge() {
  27.               return age;
  28.        }
  29.        public char getGender() {
  30.               return gender;
  31.        }
  32.        public float getScore() {
  33.               return score;
  34.        }
  35.        public void setName(String name) {
  36.               this.name = name;
  37.        }
  38.        public void setAge(int age) {
  39.               this.age = age;
  40.        }
  41.        public void setGender(char gender) {
  42.               this.gender = gender;
  43.        }
  44.        public void setScore(float score) {
  45.               this.score = score;
  46.        }
  47. }

 

解析 xml 並實現爲 JavaBean 對象賦值 :

 

  1. import java.util.List;
  2.  
  3. import org.apache.commons.beanutils.BeanUtils;
  4. import org.dom4j.Document;
  5. import org.dom4j.Element;
  6. import org.dom4j.io.SAXReader;
  7.  
  8. @SuppressWarnings("all")
  9. public class BeanUtilsDemo03 {
  10.        public static void main(String[] args) throws Exception {
  11.              
  12.               // 1. 建立一個 SAXReader 解析器
  13.               SAXReader saxReader = new SAXReader();
  14.               // 2. 讀取 xml 文檔, 獲取 docuemnt 對象
  15.               Document document = saxReader.read("employee.xml");
  16.               // 3. 獲取根標籤
  17.               Element rootElement = document.getRootElement();
  18.               // 4. 獲取beans標籤下的子標籤bean
  19.               List<Element> beanElements = rootElement.elements();
  20.               // 5.1 遍歷集合, 獲取集合中的 bean 標籤
  21.               for (Element bean : beanElements) {
  22.                     // 5.2 獲取bean標籤中的className屬性值
  23.                     String className = bean.attributeValue("className");
  24.                     // System.out.println(className);
  25.                     // 5.3 根據className字符串, 使用反射技術, 建立一個該類的實例對象
  26.                     Class<?> cls = Class.forName(className);
  27.                     Object obj = cls.newInstance();
  28.                     // 5.4 獲取 bean 標籤的 property 標籤
  29.                     List<Element> propElements = bean.elements();
  30.                     // 5.5 遍歷集合, 獲取集合中的每個 property 標籤
  31.                     for (Element prop : propElements) {
  32.                            // 5.6 獲取 prop 標籤中的 name value 屬性值
  33.                            String name = prop.attributeValue("name");
  34.                            String value = prop.attributeValue("value");
  35.                            // System.out.println(name + " = " + value);
  36.                            // 5.7 使用 BeanUtils 工具給對象的相應屬性設置數值
  37.                            BeanUtils.setProperty(obj, name, value);
  38.                     }
  39.                     System.out.println(obj);
  40.               }
  41.        }
  42. }

 

 

 

 

 

 

 

  1. 綜合案例2 (*****練習*****)

 

student.xml

<?xml version="1.0" encoding="UTF-8"?>

<students>

    <student stuNo="it001">

       <name>章子怡</name>

       <age>20</age>

       <gender></gender>

       <score>99</score>

    </student>

    <student stuNo="it002">

       <name>汪峯</name>

       <age>22</age>

       <gender></gender>

       <score>100</score>

    </student>

    <student stuNo="it003">

       <name>高圓圓</name>

       <age>18</age>

       <gender></gender>

       <score>98</score>

    </student>

</students>

 

 

Student.java

 

  1. public class Student {
  2.        // 屬性
  3.        private String stuNo;
  4.        private String name;
  5.        private int age;
  6.        private char gender;
  7.        private float score;
  8.        public Student(String stuNo, String name, int age, char gender, float score) {
  9.               super();
  10.               this.stuNo = stuNo;
  11.               this.name = name;
  12.               this.age = age;
  13.               this.gender = gender;
  14.               this.score = score;
  15.        }
  16.        public Student() {
  17.               super();
  18.        }
  19.        @Override
  20.        public String toString() {
  21.               return "Student [stuNo=" + stuNo + ", name=" + name + ", age=" + age + ", gender=" + gender + ", score=" + score
  22.                            + "]";
  23.        }
  24.        public String getStuNo() {
  25.               return stuNo;
  26.        }
  27.        public String getName() {
  28.               return name;
  29.        }
  30.        public int getAge() {
  31.               return age;
  32.        }
  33.        public char getGender() {
  34.               return gender;
  35.        }
  36.        public float getScore() {
  37.               return score;
  38.        }
  39.        public void setStuNo(String stuNo) {
  40.               this.stuNo = stuNo;
  41.        }
  42.        public void setName(String name) {
  43.               this.name = name;
  44.        }
  45.        public void setAge(int age) {
  46.               this.age = age;
  47.        }
  48.        public void setGender(char gender) {
  49.               this.gender = gender;
  50.        }
  51.        public void setScore(float score) {
  52.               this.score = score;
  53.        }
  54. }

 

StudentDemo01.java

 

  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. import org.apache.commons.beanutils.BeanUtils;
  5. import org.dom4j.Document;
  6. import org.dom4j.Element;
  7. import org.dom4j.io.SAXReader;
  8.  
  9. @SuppressWarnings("all")
  10. public class StudentDemo01 {
  11.        public static void main(String[] args) throws Exception {
  12.               // 建立一個集合, 存儲 Student 類型的對象
  13.               ArrayList<Student> list = new ArrayList<Student>();
  14.              
  15.               // 解析 xml
  16.               SAXReader saxReader = new SAXReader();
  17.               Document document = saxReader.read("student.xml");
  18.               Element rootElement = document.getRootElement();
  19.               List<Element> stuElements = rootElement.elements();
  20.               for (Element stu : stuElements) {
  21.                     // 獲取 stuNo 的屬性值
  22.                     String stuNo = stu.attributeValue("stuNo");
  23.                     System.out.println(stuNo);
  24.                     // 建立一個學生對象, 併爲學生對象的 stuNo 的屬性賦值
  25.                     Student s = new Student();
  26.                     s.setStuNo(stuNo);
  27.                     // 再獲取 stu 標籤下的全部子標籤
  28.                     List<Element> elements = stu.elements();
  29.                     for (Element element : elements) {
  30.                            String name = element.getName();   // 獲取標籤名
  31.                            String value = element.getText();  // 獲取標籤中的文本信息
  32.                            System.out.println("\t" + name + " = " + value);
  33.                            // name value 賦值給建立的學生對象
  34.                            BeanUtils.setProperty(s, name, value);
  35.                     }
  36.                     // 將建立的 Student 對象添加到集合中
  37.                     list.add(s);
  38.               }
  39.              
  40.               // 遍歷查看集合
  41.               for (Student stu : list) {
  42.                     System.out.println(stu);
  43.               }
  44.        }
  45. }

 

輸出結果 :

相關文章
相關標籤/搜索