簡體   English   中英

Spring Boot 2.1.5 無法將 java.lang.String 類型的屬性值轉換為所需類型 java.time.LocalDate

[英]Spring Boot 2.1.5 Failed to convert property value of type java.lang.String to required type java.time.LocalDate

我正在嘗試使用 Thymeleaf 作為我的模板引擎來設置 Spring Boot 2.1.5/Spring MVC 應用程序。 我有一個 bean 將支持我的表單(為簡潔起見,省略了 getter 和 setter):

 public class SchoolNightForm {

    private String orgName;
    private String address;
    private String location;
    private String city;
    private String state;
    private String zip;
    private String contactName;
    private String phone;

    @NotEmpty(message = "Enter a valid email.")
    private String email;

    @Positive(message = "Value must be positive.")
    private int totalStudents;

    private LocalDate dateRequested;
}

HTML模板:

  <div class='form-group col-sm-9'>
                <label for='dateRequested'>Date Requested</label>
                <input type='date'  required class='form-control' id='dateRequested' name='dateRequested'
                    th:field='*{dateRequested}' />
                    <small class='text-danger' th:if="${#fields.hasErrors('dateRequested')}" th:errors='*{dateRequested}'>Valid date required</small>
            </div>

根據Thymeleaf 文檔,我配置了一個轉換服務:

    @Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(dateFormatter());
    }

    @Bean
    public DateFormatter dateFormatter() {
        return new DateFormatter("yyyy-MM-dd");
    }
}

我最初使用默認的 DateFormatter 實現(未提供 String 格式),但是,在查看錯誤消息並查看表單傳遞給控制器​​的格式之后,我對其進行了相應的修改:

Failed to convert property value of type java.lang.String to required type java.time.LocalDate for property dateRequested; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.time.LocalDate] for value 2019-05-28; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2019-05-28]

我的控制器方法:

@GetMapping(value = "school-night")
public String getSchoolNight(Model model) {
    model.addAttribute("schoolNightForm", new SchoolNightForm());
    return "bk-school-night";
}

@PostMapping(value = "school-night")
public String postSchoolNigh(@Valid SchoolNightForm schoolNightForm, BindingResult result)
        throws MessagingException {
    if (result.hasErrors()) {
        return "bk-school-night";
    }
    emailService.schoolNightFotm(schoolNightForm);
    return "confirm";
}

在發布請求期間發生此錯誤。 任何意見,將不勝感激。

我給你的建議是,在 dto 中接受一個日期作為字符串。 但是,如果需要使用DateTimeFormatter來獲取日期,就像這樣:

private final static DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

然后在您的方法中使用它,來回轉換它:

public class SchoolNightForm {

    private String orgName;
    private String address;
    private String location;
    private String city;
    private String state;
    private String zip;
    private String contactName;
    private String phone;

    @NotEmpty(message = "Enter a valid email.")
    private String email;

    @Positive(message = "Value must be positive.")
    private int totalStudents;

    private String dateRequested;
}

然后只需使用聲明的格式化程序來解析和格式化

FORMATTER.format(...); // your temporal accessor like Instant or LocalDateTime
FORMATTER.parse(...); // your string like "2010-01-01"

首先制作 LocalDateConverter

public class LocalDateToStringConverter implements Converter<LocalDate, String> {

@Override
public String convert(LocalDate localDate) {
    return localDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
  }
}

之后在 public static void 主類中的 ConversionService 中注冊它。 例如:

@SpringBootApplication
@PropertySources({ @PropertySource("classpath:application.properties") })

public class YourApplication {

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

    ConversionService conversionService = DefaultConversionService.getSharedInstance();
    ConverterRegistry converters = (ConverterRegistry) conversionService;
    converters.addConverter(new LocalDateToStringConverter())

   }

}

我的POM

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jersey</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

應用程序屬性

spring.thymeleaf.enable-spring-el-compiler=true
spring.thymeleaf.servlet.content-type=application/xhtml+xml
spring.main.allow-bean-definition-overriding=true
log4j.logger.org.thymeleaf = DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.CONFIG = TRACE

錯誤,我說 String 不能轉換為 LocalDate.Perhaps 你可以添加

 @JsonDeserialize(using = LocalDateDeserializer.class) // Added
 private LocalDate dateRequested;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM