我有一个spring boot post控制器,该控制器的日期带有特定格式的参数,问题是,如果用户以其他格式提交表单,应用程序将崩溃,我不确定如何处理有了这个:( 控制器:
@RequestMapping(value = "/findFlights", method = RequestMethod.POST)
public String findFlights(@RequestParam("from") String from, @RequestParam("to") String to,
@RequestParam("departureDate") @DateTimeFormat(pattern = "MM-dd-yyyy") Date departureDate, Model model) {
List<Flight> flights = flightRepository.findFlights(from, to, departureDate);
if(flights.isEmpty()) {
model.addAttribute("msg", "No flights were found!");
}else {
model.addAttribute("flights", flights);
foundFlights = true;
model.addAttribute("foundFlights", foundFlights);
}
return "displayFlights";
}
基本上,如果提交的日期是这样的:22-22-2018它会给我这个例外:
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 @org.springframework.format.annotation.DateTimeFormat java.util.Date] for value '22-22-2018'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [22-22-2018]
但是如果日期是例如:2018年10月15日,它将起作用...什么是处理此问题的最佳方法?
答案 0 :(得分:2)
您可以执行以下操作之一: