Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

java - How to register global databinding for LocalDate in spring mvc?

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 valid formats yyyyMMdd, yyyy-MM-dd, yyMMdd, yy-MM-dd.

Therefor I'm trying to register my own converter for that class and register it globally for the whole application. But it is never picked up

Problem: my custom editor is never called.

@Bean
public CustomEditorConfigurer init() {
    CustomEditorConfigurer c = new CustomEditorConfigurer();
    c.setPropertyEditorRegistrars(new PropertyEditorRegistrar[] {
            (registry) -> registry.registerCustomEditor(LocalDate.class, new LocalDatePropertyEditor())
    });
    return c;
}

public class LocalDatePropertyEditor extends PropertyEditorSupport {
    @Override
    public void setAsText(String text) {
        this.setValue(LocalDate.parse(text, DateTimeFormatter.ISO_DATE));
    }

    @Override
    public String getAsText() {
        return this.getValue().toString();
    }
}


@RestController
public void DateServlet {
    @RequestMapping("/test")
    public void test(@RequestParam LocalDate date) {

    }
}

When calling: localhost:8080/test?date=2017-07-05

Exception: Parse attempt failed for value [2017-07-05]

During debug I can see the LocalDatePropertyEditor class is never called. But why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...