springboot:接收date類型的參數(shù)
今天有個postmapping方法,地址都正確,就是死活進不去,真是奇怪了。
終于從日志中得出些端倪,見下:

只有這個屬性報錯,恰恰這個屬性是Date型。
這句話說得更清楚:
"defaultMessage":"Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'expireTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@com.alibaba.fastjson.annotation.JSONField java.util.Date] for value '2018-06-29'; nested exception is java.lang.IllegalArgumentException",
查找資料,說只要在字段上加上注解:@DateTimeFormat(pattern="yyyy-MM-dd")
加上后就一切OK了。
springboot 傳遞Date等實體參數(shù)時候報錯
傳遞參數(shù)Date時候報錯:
"exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
"message": "Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam java.util.Date] for value '2016-12-27 09:44:58'; nested exception is java.lang.IllegalArgumentException",
swagger2:
@ApiImplicitParam(name = "startDate", paramType = "query", value = "生效時間", dataType = "Date"),
@ApiImplicitParam(name = "endDate", paramType = "query", value = "失效時間", dataType = "Date"),
params由:
1
2
|
@RequestParam (value = "startDate" , required = false ) Date startDate, @RequestParam (value = "endDate" , required = false ) Date endDate, |
改為:
1
2
|
@ModelAttribute Date startDate, @ModelAttribute Date endDate, |
此時 參數(shù)傳遞正常 但是date值都存在切為當前時間
改回
1
2
|
@RequestParam (value = "startDate" , required = false ) Date startDate, @RequestParam (value = "endDate" , required = false ) Date endDate, |
并加入
1
2
3
4
|
@InitBinder protected void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Date. class , new CustomDateEditor( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ), true )); } |
此時參數(shù)傳遞正常
時間段查詢條件
1
2
3
4
5
6
7
8
9
|
if (startDate!= null ) { //開始時間 if (endDate!= null ){ //結(jié)束時間 結(jié)束時間部位空 查詢時間段內(nèi)數(shù)據(jù) predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get( "endDate" ).as(Date. class ), startDate )); //輸入開始時間>=開始生效時間 predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get( "startDate" ).as(Date. class ), endDate )); //輸入結(jié)束時間<=失效時間 } else { predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get( "startDate" ).as(Date. class ), startDate )); predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get( "endDate" ).as(Date. class ), startDate )); } } |
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/huiy/p/9047613.html