0
点赞
收藏
分享

微信扫一扫

java controller Date日期型参数异常的处理方法

介绍

springboot中controller接收Date参数有两种写法,一种是在Date参数上使用注解@DateTimeFormat(pattern=“yyyy-MM-dd HH:mm:ss”),还有一种办法是在controller中添加initBinder。

这两种方法对独立的Date参数或Vo对象中的Date参数都有效,且支持传入null值。

如果不正确处理会报异常

Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date'

方法一

第一种,在Date参数上使用注解@DateTimeFormat(pattern=“yyyy-MM-dd HH:mm:ss”)

独立参数写法

@RequestMapping("/test")
public String test(String echo,@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date testDate){
    System.out.println("echo="+echo+",testDate="+testDate);
    return "testDate="+testDate;
}

Vo参数写法

public class EchoVo {
    private String echo;
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date testDate;
    public String getEcho() {
        return echo;
    }
    public void setEcho(String echo) {
        this.echo = echo;
    }
    public Date getTestDate() {
        return testDate;
    }
    public void setTestDate(Date testDate) {
        this.testDate = testDate;
    }
}

方法二

第二种,在controller中添加initBinder

@InitBinder
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

独立Date参数示例接口

@RequestMapping("/test")
public String test(String echo, Date testDate){
    System.out.println("echo="+echo+",testDate="+testDate);
    return "testDate="+testDate;
}

Vo对象参数示例接口

@RequestMapping("/testVo")
public String testVo(EchoVo echoVo){
  System.out.println("echo="+echoVo.getEcho()+",testDate="+echoVo.getTestDate());
  return "testDate="+echoVo.getTestDate();
}

在使用SpingMVC框架的项目中,经常会遇到页面某些数据类型是Date、Integer、Double等的数据要绑定到控制器的实体,或者控制器需要接受这些数据,如果这类数据类型不做处理的话将无法绑定。

这里我们可以使用注解@InitBinder来解决这些问题,这样SpingMVC在绑定表单之前,都会先注册这些编辑器。一般会将这些方法些在BaseController中,需要进行这类转换的控制器只需继承BaseController即可。其实Spring提供了很多的实现类,如CustomDateEditor、CustomBooleanEditor、CustomNumberEditor等,基本上是够用的。

举报

相关推荐

0 条评论