BeanUtils主要用于简化JavaBean封装数据的操作。
简化反射封装参数的步骤,给对象封装参数。
好处: BeanUtils给对象封装参数的时候会进行类型自动转换。
例如:可以自动从String类型转到int,float,double类型,但是不能直接从String类型转到Date类型。
JavaBean是一个类,必须由public修饰,必须具有无参数构造器,必须提供getter和setter方法访问属性。
例如:
import java.util.Date;
public class Student {
private String stuNo;
private String stuName;
private int gender;
private int age;
private int score;
private Date birthday;
/**
* @return the stuNo
*/
public String getStuNo() {
return stuNo;
}
/**
* @param stuNo the stuNo to set
*/
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
/**
* @return the stuName
*/
public String getStuName() {
return stuName;
}
/**
* @param stuName the stuName to set
*/
public void setStuName(String stuName) {
this.stuName = stuName;
}
/**
* @return the gender
*/
public int getGender() {
return gender;
}
/**
* @param gender the gender to set
*/
public void setGender(int gender) {
this.gender = gender;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the score
*/
public int getScore() {
return score;
}
/**
* @param score the score to set
*/
public void setScore(int score) {
this.score = score;
}
/**
* @return the birthday
*/
public Date getBirthday() {
return birthday;
}
/**
* @param birthday the birthday to set
*/
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Student [stuNo=" + stuNo + ", stuName=" + stuName + ", gender=" + gender + ", age=" + age + ", score="
+ score + ", birthday=" + birthday + "]";
}
}
如果要给Student类对象的属性赋值,可以选择调用set方法,显然比较麻烦。
另一种方式是利用BeanUtils工具类给Student类对象的属性赋值。
BeanUtils相关jar包
commons-beanutils-1.9.3.jar
commons-logging-1.2.jar
commons-collections-3.2.1.jar
简单应用(处理form表单提交的学生信息):
1、如果form表单中的数据不需要从String类型转向Date类型。只需要从String类型转向int,float,或者double类型。只需要调用BeanUtils中的populate(Object bean, Map
Map map = request.getParameterMap();
Student stu = new Student();
try {
BeanUtils.populate(stu, map);
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (InvocationTargetException e1) {
e1.printStackTrace();
}
2、如果form表单中的数据需要从String类型转向Date类型。需要调用BeanUtilsBean中的populate(Object bean, Map
如果想要将form表单的数据赋值给一个bean对象,可以封装一个FormUtil类。再使用BeanUtilsBean中的populate(Object bean, Map
日期转换器代码实现:
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Locale;
import org.apache.commons.beanutils.Converter;
public class DateTimeConverter implements Converter{
//日期格式
private static final String DATE = "yyyy-MM-dd";
private static final String DATETIME = "yyyy-MM-dd HH:mm:ss";
private static final String TIMESTAMP = "yyyy-MM-dd HH:mm:ss.SSS";
@Override
public Object convert(Class type, Object value) {
return toDate(type, value);
}
//转向日期类型
//value为form提交日期字符串
public static Object toDate(Class type, Object value) {
if (value == null || "".equals(value))
return null;
if (value instanceof String) {
String dateValue = value.toString().trim();
int length = dateValue.length();
if (type.equals(java.util.Date.class)) {
try {
DateFormat formatter = null;
if (length <= 10) {
formatter = new SimpleDateFormat(DATE, new DateFormatSymbols(Locale.CHINA));
return formatter.parse(dateValue); //以DATE格式返回
}
if (length <= 19) {
formatter = new SimpleDateFormat(DATETIME, new DateFormatSymbols(Locale.CHINA));
return formatter.parse(dateValue); //以DATETIME格式返回
}
if (length <= 23) {
formatter = new SimpleDateFormat(TIMESTAMP, new DateFormatSymbols(Locale.CHINA));
return formatter.parse(dateValue); //以TIMESTAMP格式返回
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return value;
}
}
接下来就需要在FormUtil中调用日期转换器,将String类型转换成Date类型,再调用BeanUtilsBean中的populate(Object bean, Map
FormUtil类代码实现:
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.beanutils.PropertyUtilsBean;
public class FormUtil {
//生成bean对象
public static Object formToBean(HttpServletRequest request, Class beanClass) {
ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean();
convertUtilsBean.deregister(Date.class);//将默认的日期转换器去掉
convertUtilsBean.register(new DateTimeConverter(), Date.class);//注册自己写的日期转换器
//实例化BeanUtilsBean
BeanUtilsBean beanUtilsBean = new BeanUtilsBean(convertUtilsBean, new PropertyUtilsBean());
Object o = null;
try {
//通过此Class类表示类创建对象
o = beanClass.newInstance();
beanUtilsBean.populate(o, request.getParameterMap());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return o;
}
}
最后只需一行代码就可以完成将form表单数据生成一个bean对象。
Student stu = (Student)FormUtil.formToBean(request,Student.class);
测试代码:
System.out.println("stu------>"+stu);
测试结果:
参考资料:
https://blog.csdn.net/h294590501/article/details/80740002
https://blog.csdn.net/lirui874125/article/details/46637195