BeanUtils介绍
1. BeanUtils
工具类,它可以一次性的把所有请求的参数注入到
JavaBean
中。
2. BeanUtils
工具类,经常用于把
Map
中的值注入到
JavaBean
中,或者是对象属性值
的拷贝操作
3. 底层用的是反射
4. BeanUtils
不是
Jdk
的类,需要导入需要的
jar
包:
commons-beanutils-1.8.0.jar
commons-logging-1.1.1.jar
应用实例:
将request中的参数注入到Furn(即JavaBean)对象
//修改一个家居对象
public void updateFurn(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Furn furn = new Furn();
try {
BeanUtils.copyProperties(furn,request.getParameterMap());
furnService.updateFurn(furn);
//重定向
response.sendRedirect(request.getContextPath()+"/manage/furnServlet?action=list");
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
优化--封装成一个方法——使用泛型
/**
* Created by IntelliJ IDEA.
* User: 加棉
* Date: 2023/8/10
* Time: 21:58
*/
package com.jiamian.furns.utils;
import org.apache.commons.beanutils.BeanUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
public class DataUtils {
public static <T> T copyProperties(T t, Map map){
try {
BeanUtils.copyProperties(t,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return t;
}
}