1. 程式人生 > >spring boot 傳遞Date 等實體引數時候報錯

spring boot 傳遞Date 等實體引數時候報錯


傳遞引數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由:
@RequestParam(value = "startDate", required = false) Date startDate,
@RequestParam(value = "endDate", required = false) Date endDate,

改為:

@ModelAttribute Date startDate,@ModelAttribute Date endDate,
此時 引數傳遞正常  但是date值都存在切為當前時間

改回
@RequestParam(value = "startDate", required = false) Date startDate,
@RequestParam(value = "endDate", required = false) Date endDate,
並加入
@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Date.class
, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true)); }
此時引數傳遞正常



時間段查詢條件
if (startDate!=null) {//開始時間
if(endDate!=null){//結束時間  結束時間部位空  查詢時間段內資料
predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("endDate").as(Date.class), startDate ));//輸入開始時間>=開始生效時間
predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("startDate").as(Date.class), endDate ));//輸入結束時間<=失效時間
}else{
        predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("startDate").as(Date.class), startDate ));
        predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("endDate").as(Date.class), startDate ));
    }
}