如何在spring mvc中注册LocalDate的全局数据绑定? [英] How to register global databinding for LocalDate in spring mvc?

查看:123
本文介绍了如何在spring mvc中注册LocalDate的全局数据绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 LocalDate 作为使用 spring创建的 Servlet 中的类型-mvc
用户应该能够以多种有效格式提供日期 yyyyMMdd,yyyy-MM-dd,yyMMdd,yy-MM-dd

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) {

    }
}

致电:
localhost:8080 / test?date = 2017-07-05


异常:
分析尝试失败[2017-07-05]

在调试期间,我可以看到永远不会调用 LocalDatePropertyEditor 类。但为什么呢?

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

推荐答案

我仍然不知道为什么 PropertyEditor 不行。
但以下解决方案有效。

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

这篇关于如何在spring mvc中注册LocalDate的全局数据绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆