溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在Java中使用BeanUtils組件

發(fā)布時間:2021-03-20 16:55:54 來源:億速云 閱讀:272 作者:Leah 欄目:編程語言

怎么在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文件。

導入核心包

  • commons-beanutils-1.9.3.jar

  • commons-logging-1.2.jar

注意:當缺少日志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ù)類型,會自動進行類型轉(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ù)類型,會自動進行類型轉(zhuǎn)換
		BeanUtils.copyProperty(s, "id","2018100712");
    System.out.println(s)
}

map數(shù)據(jù)封裝到javaBean

注意:要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)換器

當javaBean中出現(xiàn)非基本類型數(shù)據(jù)的私有化屬性,并且需要對該數(shù)據(jù)進行封裝時,就要去注冊該數(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)換器。

怎么在Java中使用BeanUtils組件

自定義類型轉(zhuǎn)換器

去復寫ConvertUtils里面的register(Converter converter, Class<?> clazz)方法

@Test
	public void test2() throws Exception {
		//假設網(wǎng)頁表單提交過來的數(shù)據(jù)
		String name="老王";
		String id="121212";
		String date="2018-10-11";
		Student s=new Student();
		//1.自定義:注冊日期類型轉(zhuǎn)換器去復寫ConvertUtils里面的register(Converter converter, Class<?> clazz)方法
		ConvertUtils.register(new Converter() {
			//修改第三方jar引入方法的參數(shù)時候,可以關聯(lián)源碼,ctrl選擇該類,點進去,選擇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ù)據(jù)
		String name="老王";
		String id="121212";
		//當日期字符串出現(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);
	}

注意:當日期字符串是空字符串或者存在空格的時候,會報錯!

BeanUtils在servlet的使用

獲取表單提交的數(shù)據(jù)并封裝到javabean中去,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>
 		密&nbsp;&nbsp;碼:<input type="password" name="password"><br>
 		聯(lián)系方式:<input type="text" name="phone"><br>
 		<input type="submit" value="提交">
 	</form>
 </body>
</html>

jsp顯示的結(jié)果:

怎么在Java中使用BeanUtils組件 

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]

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI