Spring MVC接收参数为日期类型

2017-07-21  本文已影响588人  else05

问题:

在Spring Boot的Controller中接收日期类型,格式是yyyy-MM-dd HH:mm:ss , 结果报异常

public String batchUpload(@RequestParam  LocalDateTime startTime){
// do something
}

报的异常
Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime'
如果是Date类型则为
Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'

解决方法:

先加上maven依赖:

<dependency>
     <groupId>com.fasterxml.jackson.datatype</groupId>
     <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
@InitBinder  
private void initBinder(WebDataBinder binder) {  
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
}  
注:这种方式只能处理Date类型,如果是LocalDateTime则要自己新建类,继承PropertyEditorSupport ,可以参考org.springframework.beans.propertyeditors.CustomDateEditor的实现方式
public String batchUpload(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")  LocalDateTime startTime){
// do something
}
注:前端传的日期格式为“2017-07-03 12:23:12” 。如果“2017-7-3 12:23:12”则会异常,因为匹配规则为“yyyy-MM-dd HH:mm:ss” , 除了年份,都要为两位数才行

参考:

上一篇下一篇

猜你喜欢

热点阅读