参数值[1]与预期类型不匹配

时间:2019-07-07 07:37:46

标签: java spring-boot spring-restcontroller

在Spring-boot项目中,我尝试将Date对象作为请求参数传递并得到此错误:

Parameter value [1] did not match expected type [java.util.Date (n/a)]

这是我发送的http-requset:

http://localhost:8080/moneyManager/customer/actionBetweenDates?startDate=2019/07/01&endDate=2019/07/30

这是触发其余功能的功能:

@RequestMapping(path="actionBetweenDates", method=RequestMethod.GET)
public Collection<Action> getActionByDate(@RequestParam Date startDate, @RequestParam Date endDate){
    return customerService.getAllActionBetweenDate(getSession().getId(), startDate, endDate);
}

静态功能触发服务中的功能:

public Collection<Action> getAllActionBetweenDate(long customerId, Date startDate, Date endDate) {
        Collection<MethodPayment> customerMethodPayments = methodPaymentRepository.findByCustomerId(customerId);
        Collection<Action> customerActionByDates = new ArrayList<>();
        for (MethodPayment mp : customerMethodPayments) {
            customerActionByDates
                    .addAll(actionRepository.findByDateBetweenAndMethodPaymentId(mp.getId(), startDate, endDate));
        }
        return customerActionByDates;
    }

服务中的函数触发存储库中的功能:

Collection<Action> findByDateBetweenAndMethodPaymentId(long methodPaymentId, Date startDate, Date endDate);

我在做什么错了?

更新:

我找到了问题。 问题与在actionRepository中找到的功能有关。 该函数的签名首先要求两个日期进行比较,然后是id,然后我给它提供了相反的值。 对我来说很明显,我上完日期后会遇到问题,因此答案确实对我有帮助。 谢谢大家!

1 个答案:

答案 0 :(得分:1)

将您的控制器方法更改为:

@RequestMapping(path="actionBetweenDates", method=RequestMethod.GET)
public Collection<Action> getActionByDate(@RequestParam @DateTimeFormat(pattern = "yyyy/MM/dd") Date startDate, @RequestParam @DateTimeFormat(pattern = "yyyy/MM/dd") Date endDate){
    return customerService.getAllActionBetweenDate(getSession().getId(), startDate, endDate);
}

检查Annotation Type DateTimeFormat以获得详细信息,有关用法示例,请查看Working with Date Parameters in Spring


UPD 1:
添加示例@SpringBootApplication类和示例请求:

@SpringBootApplication
@RestController
public class DateProblemApp {

    public static void main(String[] args) {
        SpringApplication.run(DateProblemApp.class, args);
    }

    @RequestMapping(path="actionBetweenDates", method = RequestMethod.GET)
    public String getActionByDate(@RequestParam @DateTimeFormat(pattern = "yyyy/MM/dd") Date startDate, @RequestParam @DateTimeFormat(pattern = "yyyy/MM/dd") Date endDate) {
        return "ok";
    }

}

示例请求:http://localhost:8080/actionBetweenDates?startDate=2019/07/01&endDate=2019/07/30