Java類庫BeanUtils組件使用方法及實例詳解
BeanUtils
BeanUtils是Apache commens組件里面的成員,由Apache提供的一套開源api,用于簡化對javaBean的操作,能夠?qū)绢愋妥詣愚D(zhuǎn)換。
JavaBean
BeanUtils組件是用于簡化javaBean的操作,那么什么是javaBean呢?簡單來說,javaBean實質(zhì)就是java類,只不過是遵循了某種規(guī)范的java類。
javaBean的特點:
- 必須具有一個無參的構(gòu)造方法
- 屬性必須私有化
- 私有化的屬性必須通過public類型的方法來暴露,也就是說要出現(xiàn)setXXX()、getXXX()或者isXXX()的方法
下載BeanUtils
http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgi,下載好組件,再到項目里面引入jar文件。
導(dǎo)入核心包
- commons-beanutils-1.9.3.jar
- commons-logging-1.2.jar
注意:當(dāng)缺少日志jar包,會出現(xiàn)如下的報錯情況。
java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
logging組件的下載地址:http://commons.apache.org/proper/commons-logging/download_logging.cgi
javaBean實例
public class Student { private String name; private String id; private int age; private String sex; private Date d; public Student() { super(); } public Date getD() { return d; } public void setD(Date d) { this.d = d; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "Student [name=" + name + ", id=" + id + ", age=" + age + ", sex=" + sex + ", d=" + d + "]"; } }
BeanUtils用法
- 對象的拷貝,BeanUtils.copyProperties(Object dest,Object orig)
- 對象屬性的拷貝,BeanUtils.copyProperties(Object bean,String name,Object value)或者BeanUtils.setProperty(Object bean,String name,Object value)
- map數(shù)據(jù)封裝到Javabean,populate(Object bean, Map<String,? extends Object> properties)
實例
對象的拷貝
@Test public void test() throws Exception { //創(chuàng)建對象 Student s=new Student(); /** * 組件對JavaBean的操作 * bean:javaBean對象 * name:對象的屬性名稱 * value:對象的屬性值 */ //1.實現(xiàn)對象的屬性拷貝, 對于基本數(shù)據(jù)類型,會自動進(jìn)行類型轉(zhuǎn)換 BeanUtils.copyProperty(s, "id","2018100712"); //2.實現(xiàn)對象之間的拷貝:Object dest<---Object orig Student s2=new Student(); BeanUtils.copyProperties(s2, s); System.out.println(s2); }
對象屬性的拷貝
@Test public void test() throws Exception { //創(chuàng)建對象 Student s=new Student(); /*一般的操作 s.setId("1221212"); s.setName("老王"); System.out.println(s); */ //1.實現(xiàn)對象的屬性拷貝, 對于基本數(shù)據(jù)類型,會自動進(jìn)行類型轉(zhuǎn)換 BeanUtils.copyProperty(s, "id","2018100712"); System.out.println(s) }
map數(shù)據(jù)封裝到j(luò)avaBean
注意:要map中的數(shù)據(jù)封裝到JavaBean中去,需要map中的key與JavaBean里面的私有化的屬性要相匹配
@Test public void test() throws Exception { //創(chuàng)建對象 Student s2=new Student(); //1.map的數(shù)據(jù)拷貝到對象中去 Map<String,Object> map = new HashMap<String,Object>(); map.put("id","12233"); map.put("name","老王"); map.put("sex","男"); BeanUtils.populate(s2, map); System.out.println(s2); }
類型轉(zhuǎn)換器
當(dāng)javaBean中出現(xiàn)非基本類型數(shù)據(jù)的私有化屬性,并且需要對該數(shù)據(jù)進(jìn)行封裝時,就要去注冊該數(shù)據(jù)類型的類型轉(zhuǎn)換器了,不如就會出現(xiàn)錯誤,比如該Student對象中的日期類型。
日期類型轉(zhuǎn)換出錯:org.apache.commons.beanutils.converters.DateConverter toDate 警告: DateConverter does not support default String to 'Date' conversion,可以看出工具類converters在轉(zhuǎn)換的時候出現(xiàn)了錯誤,為此我們可以去查看該類,以便我們接下來去實現(xiàn)類型轉(zhuǎn)換。
converter
在解壓出來的BeanUtils文件下的apidoc目錄中的index.html里面可以找到該類的說明,會發(fā)現(xiàn)它是一個接口,有很多的實現(xiàn)類,我們可以使用里面的實現(xiàn)類來做日期類型的轉(zhuǎn)換或者說我們可以自己去注冊個類型轉(zhuǎn)換器。
自定義類型轉(zhuǎn)換器
去復(fù)寫ConvertUtils里面的register(Converter converter, Class<?> clazz)方法
@Test public void test2() throws Exception { //假設(shè)網(wǎng)頁表單提交過來的數(shù)據(jù) String name="老王"; String id="121212"; String date="2018-10-11"; Student s=new Student(); //1.自定義:注冊日期類型轉(zhuǎn)換器去復(fù)寫ConvertUtils里面的register(Converter converter, Class<?> clazz)方法 ConvertUtils.register(new Converter() { //修改第三方j(luò)ar引入方法的參數(shù)時候,可以關(guān)聯(lián)源碼,ctrl選擇該類,點進(jìn)去,選擇Attach source--->external file @Override public Object convert(Class type, Object value) { //判斷 if (value ==null ||"".equals(value.toString().trim())){ return null; } if (type !=Date.class){ return null; } try { //字符串轉(zhuǎn)換為日期 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); return sdf.parse(value.toString()); } catch (Exception e) { throw new RuntimeException(e); } } },Date.class); //把表單的數(shù)據(jù)封裝到對象中去 BeanUtils.copyProperty(s, "name",name); BeanUtils.copyProperty(s, "id",id); BeanUtils.copyProperty(s, "d",date); System.out.println(s); }
使用工具類提供的類型轉(zhuǎn)換器
@Test public void test3() throws Exception { //利用組件提供的日期類型轉(zhuǎn)換器,提供一個實現(xiàn)類 //假設(shè)表單的數(shù)據(jù) String name="老王"; String id="121212"; //當(dāng)日期字符串出現(xiàn)空字符串或者出現(xiàn)空格的情況,會報錯org.apache.commons.beanutils.ConversionException String date="2018-09-12"; Student s=new Student(); ConvertUtils.register(new DateLocaleConverter(), Date.class); //把表單的數(shù)據(jù)封裝到對象中去 BeanUtils.copyProperty(s, "name",name); BeanUtils.copyProperty(s, "id",id); BeanUtils.copyProperty(s, "d",date); System.out.println(s); }
注意:當(dāng)日期字符串是空字符串或者存在空格的時候,會報錯!
BeanUtils在servlet的使用
獲取表單提交的數(shù)據(jù)并封裝到j(luò)avabean中去,request.getParameterMap()獲取所有的參數(shù)并存儲到Map中去,并利用BeanUtils里面的populate(Object bean, Map<String,? extends Object> properties),封裝到對象中去,簡化了很多的操作!
1.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>注冊</title> </head> <body> <form action="registe.do" method="post"> 用戶名稱:<input type="text" name="name"><br> 密 碼:<input type="password" name="password"><br> 聯(lián)系方式:<input type="text" name="phone"><br> <input type="submit" value="提交"> </form> </body> </html>
jsp顯示的結(jié)果:
2.servlet
package cn.tan.servlet; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils; import cn.tan.entry.Student; public class GetDataServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //獲取所有參數(shù) Map<String, String[]> map = request.getParameterMap(); Student s=new Student(); try { BeanUtils.populate(s, map); //測試,輸出封裝的結(jié)果 System.out.println(s); } catch (Exception e) { throw new RuntimeException(e); } } }
輸出結(jié)果:Student [name=老王, age=0, password=11111, phone=13232174361]
更多關(guān)于Java類庫BeanUtils組件使用方法級實例請查看下面的相關(guān)鏈接
相關(guān)文章
各種格式的編碼解碼工具類分享(hex解碼 base64編碼)
這篇文章主要介紹了各種格式的編碼解碼工具類,集成Commons-Codec、Commons-Lang及JDK提供的編解碼方法2014-01-01詳解Java?Synchronized的實現(xiàn)原理
談到多線程就不得不談到Synchronized,重要性不言而喻,今天主要談?wù)凷ynchronized的實現(xiàn)原理。文中的示例代碼講解詳細(xì),感興趣的可以了解一下2022-09-09關(guān)于@Autowierd && @Resource 你真的了解嗎
這篇文章主要介紹了關(guān)于@Autowierd && @Resource的具體使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08