How to register global databinding for LocalDate in spring mvc?

后端 未结 2 1608
無奈伤痛
無奈伤痛 2020-12-21 09:11

I\'d like to use LocalDate as type in a Servlet created with spring-mvc. The users should be able to provide the date in multiple vali

相关标签:
2条回答
  • 2020-12-21 09:14

    Well, Even I faced the problem and could not get PropertyEditor to work without initBinder():

    Adding below code to each controller would work, I am using springboot v1.5:

    @InitBinder
        public void initBinder(WebDataBinder binder) {
            binder.registerCustomEditor(LocalDate.class, 
                new LocalDateEditor());
        }
    

    But bit more easier solution apart from using WebMvcConfigurerAdapter as described by @membersound is to use converters

    @Component
    public class LocalDateSerializeConverter implements Converter<String, LocalDate> {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(AppConstants.DATE_FORMAT_YYYY_MM_DD);
    
        @Override
        public LocalDate convert(String text) {
            return LocalDate.parse(text, formatter);
        }
    }
    
    0 讨论(0)
  • 2020-12-21 09:21

    I still don't know why PropertyEditor does not work. But the following solutions worked.

    @Configuration
    public class LocalDateConfig extends WebMvcConfigurerAdapter {
        @Override
        public void addFormatters(FormatterRegistry registry) {
            super.addFormatters(registry);
            registry.addFormatterForFieldType(LocalDate.class, new Formatter<LocalDate>() {
                //override parse() and print()
            });
        }
     }
    
    0 讨论(0)
提交回复
热议问题