SpringMVC处理日期类型字段时,如果数据为空或数据格式错误,SpringMVC封装到实体类时会报异常,需要开发者编码处理。
提交后台报错
有两种解决方案:
第一解决方案是在具体Controller上添加日期类型处理
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
类CustomDateEditor是Spring包org.springframework.beans.propertyeditors提供的,构造方法如下
第二种解决方案
设计全局的Advice
package com.gf.ctrl;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
@ControllerAdvice("com")
public class BaseDateAdvice {
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
}