其实之前就遇到过这个问题,只是之前并没有做记录,现在学习springboot,看到一种比较好的处理方式就记录下来。
问题:
在提交表单到Controller的时候,如果实体中存在Date类型的参数或者参数就是Date类型的,那么在提交表单的时候会遇到提交失败的错误,通过debug发现连controller都没有进入。
解决方法:
之前在网上搜索过处理方法,现在了解的由三种。全局处理推荐第三章方法。
在实体的属性上增加@DateTimeFormat(pattern = “yyyy-MM-dd”),如下:
public class User { private Integer id; private String name; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date birthday; //省略get--set方法 }
在Controller上加入initBinder方法,如下:
@InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); }
这个是我最新发现的,用了@ControllerAdvice,此注解注解的类内注解的方法应用到所有的 @RequestMapping注解的方法。读起来绕口,直接看例子:
@ControllerAdvice public class GlobalExceptionHandler { @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } }
这个会应用到你系统中所有的请求。是不是很简单,当然这个类其实更好的用处是异常处理,详见开涛大神的博客点击进入。