Spring MVC @DateTimeFormat Spring无法在控制器上工作

eeq64g8w  于 2023-03-13  发布在  Spring
关注(0)|答案(1)|浏览(175)

所以我有一个方法,我想在其中接收一些日期,这些日期将使用@DateTimeFormat注解进行转换。

@RequestMapping( method = RequestMethod.GET)
@ResponseBody
public JsonUtil getAuditLog(
        @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.Date_TIME) Date startDate,
        @RequestParam(value = "endDate", required = false ) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date endDate,
        @RequestParam(value = "page", defaultValue = "0") Integer page ) {

但我一直听到这个:

java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.util.Date': no matching editors or conversion strategy found

所以我试了这个:

@RequestMapping( method = RequestMethod.GET)
@ResponseBody
public JsonUtil getAuditLog(
        @RequestParam(value = "startDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX") Date startDate,
        @RequestParam(value = "endDate", required = false ) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX")  Date endDate,
        @RequestParam(value = "page", defaultValue = "0") Integer page ) {

同样的错误。所以我使用了SimpleDateFormat的模式,并在我的Controller中手动转换了日期。这成功了!那么为什么@DateTimeFormat注解不起作用呢?这是在SpringMVC中,而不是在Sping Boot 中。

a5g8bdjr

a5g8bdjr1#

在您的配置xml文件中,请包含这些行,我认为这可能是问题所在。因为没有它们,它将无法识别这些注解。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=
       "http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd" 
       xmlns:mvc="http://www.springframework.org/schema/mvc">
   
   
       <mvc:annotation-driven/>

   
   
       
</beans>

保留其余配置,因为它只是包括这些行在所需的地方。

相关问题