Spring Boot 2.1.5无法将类型java.lang.String的属性值转换为所需的类型java.time.LocalDate

时间:2019-06-12 15:15:31

标签: java spring spring-boot spring-mvc thymeleaf

我正在尝试使用Thymeleaf作为模板引擎来设置Spring Boot 2.1.5 / Spring MVC应用程序。我有一个将支持我的表单的bean(为简便起见,省略了getters和setters):

 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 docs,我配置了转换服务:

    @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";
}

在发布请求期间发生此错误。任何建议将不胜感激。

3 个答案:

答案 0 :(得分:0)

错误,我是说String无法转换为LocalDate。也许您可以添加

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

答案 1 :(得分:0)

我对您的建议,请在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"

答案 2 :(得分:0)

首先创建LocalDateConverter

public class LocalDateToStringConverter implements Converter<LocalDate, String> {

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

之后,将其注册到ConversionService中的公共静态void主类中。例如:

@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>

application.properties

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