繁体   English   中英

@NumberFormat接受逗号和点,如何在InitBinder中实现这一点

[英]@NumberFormat accepts comma and dot, how to achieve this in InitBinder

如果我注释这样的命令对象字段,带有逗号和点的小数将被验证并正确绑定(我想要):

@NumberFormat(style=Style.NUMBER)
private Double amount;

但是,使用@NumberFormat以相同方式注释集合不起作用,因此我尝试在全局InitBinder重现此行为:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.addCustomFormatter(new NumberStyleFormatter()); 
}

但它仍然只接受逗号。

Spring的注释处理器代码似乎也是这样,但它们同时接受逗号和点。 我错过了什么?

public class NumberFormatAnnotationFormatterFactory extends EmbeddedValueResolutionSupport
        implements AnnotationFormatterFactory<NumberFormat> {

    @Override
    public Set<Class<?>> getFieldTypes() {
        return NumberUtils.STANDARD_NUMBER_TYPES;
    }

    @Override
    public Printer<Number> getPrinter(NumberFormat annotation, Class<?> fieldType) {
        return configureFormatterFrom(annotation);
    }

    @Override
    public Parser<Number> getParser(NumberFormat annotation, Class<?> fieldType) {
        return configureFormatterFrom(annotation);
    }


    private Formatter<Number> configureFormatterFrom(NumberFormat annotation) {
        if (StringUtils.hasLength(annotation.pattern())) {
            return new NumberStyleFormatter(resolveEmbeddedValue(annotation.pattern()));
        }
        else {
            Style style = annotation.style();
            if (style == Style.CURRENCY) {
                return new CurrencyStyleFormatter();
            }
            else if (style == Style.PERCENT) {
                return new PercentStyleFormatter();
            }
            else {
                return new NumberStyleFormatter(); // THIS CASE
            }
        }
    }
}

使用模式。

NumberStyleFormatter提供了setPattern方法,您可以在其中设置模式(正则表达式)。

@InitBinder
public void initBinder(WebDataBinder binder) {
     binder.addCustomFormatter(new NumberStyleFormatter(String pattern)); 
}

更新:正则表达式接受逗号和点^[0-9.,]+$

   System.out.println("50,000.25".matches("^[0-9.,]+$")); //true

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM