SpringBoot data binding mechanism --- Custom LocalDateTime converter

Test Case

Project Demo

  /**
     *  LocalDateTime 数据自定义绑定测试
     * @param date
     * @return
     */
    @GetMapping(value = "/bind/{date}")
    @ResponseBody
    public LocalDateTime getLocalDateTime(@PathVariable(value = "date") LocalDateTime date) {

        System.out.println("测试");
        return date;
    }

The results show call

  • LocalDateTime return value without making the process look like this
    Here Insert Picture Description

Detailed configuration

  • It focused on achieving Converter
public class LocalDateTimeConverter {

    /**
     * 因为 Spring 默认不支持将 String 类型的请求参数转换为 LocalDateTime 类型,所以我们需要自定义 converter 「转换器」完整整个转换过程
     */
    public static class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {
        @Override
        public LocalDateTime convert(String s) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.CHINESE);
            return LocalDateTime.parse(s, formatter);
        }
    }
}

Custom converter is registered container

@Configuration
public class UnifiedReturnConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        /**
         * 注册
         */
        registry.addConverter(new LocalDateTimeConverter.StringToLocalDateTimeConverter());
    }
 }

Project Demo

Published 42 original articles · won praise 19 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_37828719/article/details/103823133