首页 > 解决方案 > 无法在springboot中将'java.lang.string'的值从jsp转换为'java.localtime'

问题描述

我很陌生SpringBoot。我在将我从 jsp 表单获得的字符串值转换为 LocalTime 时遇到了一些问题。例如,我有 jsp 表单,我在其中编写输入:

<div class="col-lg-7">
    <form:input path="shiftStart" type="time" name="shiftStart" id="shift-start-time" min="08:00:00" max="17:45:00" step="900"></form:input>
</div>

我有以下控制器,我尝试将此字符串值转换为 LocalTime 变量:

@PostMapping("/add-shift")
public String createShiftForm(@ModelAttribute("shiftForm") @Valid TimeTable timeTable, BindingResult result, Model model, @RequestParam("shiftStart") String shiftStart ){
    if (result.hasErrors()) {
        return "/add-shift";
    }
   LocalTime startShift = LocalTime.parse(shiftStart);
   model.addAttribute("shiftStart",startShift);
   return "redirect:/admin";
}

我收到以下错误:

Failed to convert property value of type java.lang.String to required type java.time.LocalTime for property shiftEnd; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.persistence.Column java.time.LocalTime] for value 09:15; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [09:15]

有人可以帮忙吗?

标签: javaspring-bootdatejspdate-format

解决方案


我找到了一个解决方案:只需要在没有@RequestParametrin 的情况下传递参数Controller并将字符串转换为本地变量中的本地时间,如下所示:

 @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.TIME) LocalTime  shiftStart

这里讨论了:如何在 Spring 中使用 LocalDateTime RequestParam?我收到“无法将字符串转换为 LocalDateTime”


推荐阅读