springmvc框架提供了封装javaBean的功能,但是不会自动封装(比如java.util.Date类型),需要我们自行绑定。
这里介绍两种解决的办法:@InitBinder&@DateTimeFormat()
@InitBinder
public void initBinder(WebDataBinder binder, WebRequest request) {
//转换日期 注意这里的转化要和传进来的字符串的格式一直 如2019-09-09 就应该为yyyy-MM-dd
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text == null || text.isEmpty()) {
setValue(null);
} else {
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
try {
// 尝试第一种格式
setValue(dateFormat1.parse(text));
} catch (Exception e) {
try {
// 如果第一种格式失败,尝试第二种格式
setValue(dateFormat2.parse(text));
} catch (Exception ex) {
throw new IllegalArgumentException("Invalid date/time format");
}
}
}
}
});
}