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

只有這個(gè)屬性報(bào)錯(cuò),恰恰這個(gè)屬性是Date型。
這句話說(shuō)得更清楚:
"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",
查找資料,說(shuō)只要在字段上加上注解:@DateTimeFormat(pattern="yyyy-MM-dd")
加上后就一切OK了。
springboot 傳遞Date等實(shí)體參數(shù)時(shí)候報(bào)錯(cuò)
傳遞參數(shù)Date時(shí)候報(bào)錯(cuò):
"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 = "生效時(shí)間", dataType = "Date"),
@ApiImplicitParam(name = "endDate", paramType = "query", value = "失效時(shí)間", 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í) 參數(shù)傳遞正常 但是date值都存在切為當(dāng)前時(shí)間
改回
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í)參數(shù)傳遞正常
時(shí)間段查詢條件
1
2
3
4
5
6
7
8
9
|
if (startDate!= null ) { //開(kāi)始時(shí)間 if (endDate!= null ){ //結(jié)束時(shí)間 結(jié)束時(shí)間部位空 查詢時(shí)間段內(nèi)數(shù)據(jù) predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get( "endDate" ).as(Date. class ), startDate )); //輸入開(kāi)始時(shí)間>=開(kāi)始生效時(shí)間 predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get( "startDate" ).as(Date. class ), endDate )); //輸入結(jié)束時(shí)間<=失效時(shí)間 } else { predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get( "startDate" ).as(Date. class ), startDate )); predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get( "endDate" ).as(Date. class ), startDate )); } } |
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/huiy/p/9047613.html