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

你。 提交于 2020-03-05 03:52:07

问题


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.


回答1:


My advice to you, accept a date as a string in the dto. However, if needed use DateTimeFormatter to get the date, just like this:

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

Then use it in your method, to convert it back and forth:

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

Then just use declared formatter to parse and format

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



回答2:


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



回答3:


By error, I am saying String cannot be converted to LocalDate.Perhaps you could add

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


来源:https://stackoverflow.com/questions/56565496/spring-boot-2-1-5-failed-to-convert-property-value-of-type-java-lang-string-to-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!