繁体   English   中英

无法将 java.lang.String 类型的值转换为所需的 java.util.Date 类型

[英]Failed to convert value of type java.lang.String to required type java.util.Date

<form th:action="@{home}" method="get">
    <div class="form-group">
        <label>from date:</label> <input type="date" pattern="yyyy-MM-dd" name="d1" th:value="${d1}" />
        <label>to date:</label> <input type="date" pattern="yyyy-MM-dd"  name="d2" th:value="${d2}" />
        <button type="submit">Trouver</button>
    </div>
</form>

这是控制器代码部分:

@RequestParam(name = "d1", defaultValue = "1900-01-01") @DateTimeFormat(pattern = "yyyy-MM-dd") Date d1,
        @RequestParam(name = "d2", defaultValue = "2200-01-01") @DateTimeFormat(pattern = "yyyy-MM-dd") Date d2){

我收到这条消息:

出现意外错误(类型=错误请求,状态=400)。 无法将类型 [java.lang.String] 的值转换为所需类型 [java.util.Date]; 嵌套异常是 org.springframework.core.convert.ConversionFailedException:无法从类型 [java.lang.String] 转换为类型 [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.util.Date] 值 'Wed Jun 08 00:00:00 WET 2016'; 嵌套异常是 java.lang.IllegalArgumentException:解析尝试失败的值 [Wed Jun 08 00:00:00 WET 2016]

您为 html 输入元素提供的模式无法按您的预期工作。 您没有为此设置日期格式,正如您从错误消息中看到的那样,spring 尝试解析的日期是

Wed Jun 08 00:00:00 WET 2016

不是您在 html 和控制器中设置的格式的任何日期(html 模式不会修改发送的格式,它用于验证目的)。

我从来没有用过,但你也应该

  • 只需删除完整的模式和格式,看看是否有效(我想可以)
  • 根据我上面发布的日期格式(以及您的错误消息),在您的控制器模式中设置正确的日期格式。

这里:

@DateTimeFormat(pattern = "yyyy-MM-dd")

您已使用注释@DateTimeFormat(pattern = "yyyy-MM-dd") 在控制器类中正确设置了模式。 并且还请确保您已经: 在您的模型/实体类中导入了两个必需的模式:

import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Temporal(TemporalType.DATE)
private Date date;

希望它起作用。因为它对我的起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM