1. 前台传过来的数据都是字符串, 基本类型BeanUtils会自动转换, 日期类型需要注册转换器,自带的DateLocalConvert转换器未实现空字符串""的判断
public static <T> T copy2Bean(HttpServletRequest request, Class<T> clazz) { ConvertUtils.register(new Converter() {//注册日期转换器 public Object convert(Class type, Object value) { if(type != Date.class) return null; if(value != null || "".equals(value.toString().trim())) return null; try { return new SimpleDateFormat("yyyy-MM-dd").parse(value.toString()); } catch (ParseException e) { throw new RuntimeException(e); } } }, clazz); try { T t = clazz.newInstance();//1.获取类型的对象 //封装请求数据方式1, 推荐 Map map = request.getParameterMap(); BeanUtils.populate(t, map); //封装请求数据方式2 // Enumeration headerNames = request.getParameterNames(); // while(headerNames.hasMoreElements()){ // String key = (String) headerNames.nextElement(); // String value = request.getParameter(key); // BeanUtils.copyProperty(t, key, value); // } return t; } catch (Exception e) { throw new RuntimeException(e); } }