springmvc请求时间参数报错

来源:互联网 发布:大数据都包括什么 编辑:程序博客网 时间:2024/06/07 11:09

其实之前就遇到过这个问题,只是之前并没有做记录,现在学习springboot,看到一种比较好的处理方式就记录下来。

问题:

在提交表单到Controller的时候,如果实体中存在Date类型的参数或者参数就是Date类型的,那么在提交表单的时候会遇到提交失败的错误,通过debug发现连controller都没有进入。

解决方法:

之前在网上搜索过处理方法,现在了解的由三种。全局处理推荐第三章方法。

  1. 在实体的属性上增加@DateTimeFormat(pattern = “yyyy-MM-dd”),如下:

     public class User {    private Integer id;    private String name;    @DateTimeFormat(pattern = "yyyy-MM-dd")    private Date birthday;    //省略get--set方法}
  2. 在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));    }
  3. 这个是我最新发现的,用了@ControllerAdvice,此注解注解的类内注解的方法应用到所有的 @RequestMapping注解的方法。读起来绕口,直接看例子:

    @ControllerAdvicepublic 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));    }}

这个会应用到你系统中所有的请求。是不是很简单,当然这个类其实更好的用处是异常处理,详见开涛大神的博客点击进入。

0 0