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

查看:27
本文介绍了Spring Boot 2.1.5 无法将 java.lang.String 类型的属性值转换为所需类型 java.time.LocalDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 公开课 SchoolNightForm {私人字符串组织名称;私有字符串地址;私人字符串位置;私人弦城;私有字符串状态;私人字符串拉链;私人字符串联系人姓名;私人字符串电话;@NotEmpty(message = "请输入有效的电子邮件.")私人字符串电子邮件;@Positive(message = "值必须为正.")private int totalStudents;私人 LocalDate 日期请求;}

HTML 模板:

 

<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}'>需要有效日期</small>

根据 Thymeleaf 文档,我配置了一个转换服务:

 @Configuration公共类 WebConfig 实现 WebMvcConfigurer {@覆盖public void addFormatters(FormatterRegistry registry) {registry.addFormatter(dateFormatter());}@豆角,扁豆公共 DateFormatter dateFormatter() {return new DateFormatter("yyyy-MM-dd");}}

我最初使用默认的 DateFormatter 实现(未提供字符串格式),但是,在查看错误消息并查看表单传递给控制器​​的格式之后,我对其进行了相应的修改:

未能将 java.lang.String 类型的属性值转换为属性 dateRequested 所需的类型 java.time.LocalDate;嵌套异常是 org.springframework.core.convert.ConversionFailedException:无法从类型 [java.lang.String] 转换为值 2019-05-28 的类型 [java.time.LocalDate];嵌套异常是 java.lang.IllegalArgumentException:解析尝试失败的值 [2019-05-28]

我的控制器方法:

@GetMapping(value = "school-night")公共字符串 getSchoolNight(模型模型){model.addAttribute("schoolNightForm", new SchoolNightForm());return "bk-school-night";}@PostMapping(value = "学校之夜")public String postSchoolNigh(@Valid SchoolNightForm schoolNightForm, BindingResult 结果)抛出消息异常{如果(result.hasErrors()){return "bk-school-night";}emailService.schoolNightFotm(schoolNightForm);返回确认";}

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

解决方案

先制作LocalDateConverter

public class LocalDateToStringConverter 实现 Converter{@覆盖公共字符串转换(LocalDate localDate){return localDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));}}

然后在 public static void 主类的 ConversionService 中注册它.例如:

@SpringBootApplication@PropertySources({ @PropertySource("classpath:application.properties") })公共类你的应用{公共静态无效主(字符串 [] args){SpringApplication.run(YourApplication.class, args);ConversionService ConversionService = DefaultConversionService.getSharedInstance();ConverterRegistry 转换器 = (ConverterRegistry) 转换服务;converters.addConverter(new LocalDateToStringConverter())}}

我的 POM

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

application.properties

spring.thymeleaf.enable-spring-el-compiler=truespring.thymeleaf.servlet.content-type=application/xhtml+xmlspring.main.allow-bean-definition-overriding=truelog4j.logger.org.thymeleaf = 调试log4j.logger.org.thymeleaf.TemplateEngine.CONFIG = TRACE

I am attempting set up a Spring Boot 2.1.5 / Spring MVC app using Thymeleaf as my template engine. I have a bean that will be backing my form (getters and setters omitted for brevity):

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

The HTML template:

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

Per the Thymeleaf docs, I configured a conversion service:

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

I initially used the default DateFormatter implementation (no String format provided), but, after, reviewing the error message, and seeing the format that the form was passing to the controller, I modified it accordingly:

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]

My controller methods:

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

This error occurs during the post request. Any advice would be appreciated.

解决方案

First make LocalDateConverter

public class LocalDateToStringConverter implements Converter<LocalDate, String> {

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

After that register it in the ConversionService in the public static void main class. For example:

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

   }

}

My 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

这篇关于Spring Boot 2.1.5 无法将 java.lang.String 类型的属性值转换为所需类型 java.time.LocalDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆