一般这样用:
表单的数据封装到一个bean里面,然后验证数据是否合格,如果合格了,再把表单的bean复制给另一个bean,比如数据库中学生(Student)bean
复制bean的方法:
也要导入bean的开发包
/*
第一个bean所有字段
private String username;
private String password;
private String password2;
private String email;
private String birthday;
private String nickname;
第二个bean所有字段
private String id;
private String username;
private String password;
private String email;
private Date birthday;
private String nickname;
* */
public static void copyBean(Object src,Object dest){
//自定义一个转换器:把string型的日期转换成日期格式:
ConvertUtils.register(new Converter() {
@Override
public Object convert(Class type, Object value) {
if (value == null)
return null;
String str = (String) value;
if (str.trim().equals(""))
return null;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
return df.parse(str.trim());
} catch (ParseException e) {
throw new RuntimeException();
}
}
}, Date.class);
try {
//转换完数据格式接着进行复制
BeanUtils.copyProperties(dest, src);
} catch (Exception e) {
throw new RuntimeException();
}
调用上面方法实现bean复制:
例如把表单相关的bean复制给user的bean
User user=new User();
copyBean(form, user);