package cn.gdpe.jdbc;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtils;
import cn.gdpe.bean.User;
public class WebBeanUtil {
//原始
public static void copyToBean(HttpServletRequest request,Object object){
try {
// T object=clazz.newInstance();
Enumeration<String> en = request.getParameterNames();//获取所有表单名字
while(en.hasMoreElements()){
String name=en.nextElement();//获取name值
String value=request.getParameter(name);
BeanUtils.copyProperty(object,name,value);
// BeanUtils.setProperty(object,name,value);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//这种应用到了泛型
public static <T> T copyToBean2(HttpServletRequest request,Class<T> clazz){
try {
T object=clazz.newInstance();
Enumeration<String> en = request.getParameterNames();//获取所有表单名字
while(en.hasMoreElements()){
String name=en.nextElement();//获取name值
String value=request.getParameter(name);
BeanUtils.copyProperty(object,name,value);
// BeanUtils.setProperty(object,name,value);
//
}
return object;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/*
* 支持这种方法
*/
public static <T> T copyToBean3(HttpServletRequest request,Class<T> clazz){
try {
T object=clazz.newInstance();
BeanUtils.populate(object, request.getParameterMap());
return object;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}