BeanUtils工具类,简化数据封装,用于封装javabean
在整个J2EE的编程过程中,我们经常会从各种配置文件中读取相应的数据,需要明白的一点是从配置文件中读取到的数据都是String,但是很显然我们的应用程序中不仅仅有String一种数据类型,比如:基本数据类型(int、double、char、float等),还有自定义数据类型(引用数据类型)使用BeanUtils可直接将String类型转换成对应的对象的属性类型。
要求 1.类必须被public修饰 2.必须提供空参构造方法 3.成员变量必须用private修饰 4.提供set和get方法
需要倒入 commons-beanutils-1.9.4.jar
测试:
package test;
import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;
import java.lang.reflect.InvocationTargetException;
public class BeanUtilsTest {
@Test
public void test() {
User user = new User();
try {
BeanUtils.setProperty(user, "usernamae", "111");
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(user);
}
}
上一篇文章中Loginservlet中
//3创建User对象
User loginUser = new User();
//3.2使用BeanUtils封装
try {
BeanUtils.populate(loginUser,request.getParameterMap());//注意是apeach下的beans,有两个beans
System.out.println(loginUser);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
可以用Map<String, String[]> map = request.getParameterMap(); 创建map替代request.getParameterMap()
map里的数据是key-value 键值对
BeanUtils.populate(object,map)将map中的键对应Object中的属性
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
需要注意的是map中的键需要为属性名Username-->username 需要对应好