首页 > 代码库 > 这是个非常强悍的beanutils工具

这是个非常强悍的beanutils工具

注:需要的jar包两个(缺一不可): commons-beanutils-1.8.3.jar;commons-logging-1.1.1.jar


package cn.test1;


import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;


import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;


//当表单提交时就通过反射向一个bean里面添加提交过来的数据
public class WebUtil {
public static <T> T request2Bean(HttpServletRequest request,Class<T> BeanClass){
T bean;
try {
//通过反射创建一个封装数据的bean
bean = BeanClass.newInstance();
//把request中数据添加到bean中 
Enumeration<String> e = request.getParameterNames();
while(e.hasMoreElements()){
String value = http://www.mamicode.com/null;
StringBuffer sb = new StringBuffer();
//取出bean中的字段名
String name = (String) e.nextElement();
// 如果是一个多选框
if("enjon".equals(name)){
String[] str = request.getParameterValues(name);
for (int i = 0; i < str.length; i++) {
if(i==(str.length)-1) {
sb.append(str[i]);
}else{
sb.append(str[i]+",");
}
}
value = http://www.mamicode.com/sb.toString();
}else{
//获取到每个字段上的值
value = http://www.mamicode.com/request.getParameter(name);
}
//把值赋给每一个字段上
BeanUtils.setProperty(bean,name,value);
}
return bean;
} catch (Exception e) {
throw new RuntimeException(e);
}
}

//注册一个日期转换器
public static void copyBean(Object src,Object dest){
ConvertUtils.register(new Converter(){
public Object convert(Class type,Object value){
if(value=http://www.mamicode.com/=null){
return null;
}
String str = (String)value;
if(str.trim().equals("")){
return null;
}
SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
try {
return sm.parse(str);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
},Date.class);
try {
BeanUtils.copyProperties(dest,src);
} catch (Exception e) {
throw new RuntimeException(e);
}

}

//产生一个全球唯一的ID
public static String generateId(){
return UUID.randomUUID().toString();
}


}