How to register global databinding for LocalDate in spring mvc?

后端 未结 2 1607
無奈伤痛
無奈伤痛 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 {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(AppConstants.DATE_FORMAT_YYYY_MM_DD);
    
        @Override
        public LocalDate convert(String text) {
            return LocalDate.parse(text, formatter);
        }
    }
    

提交回复
热议问题