【问题标题】:@NumberFormat accepts comma and dot, how to achieve this in InitBinder@NumberFormat 接受逗号和点,如何在 InitBinder 中实现
【发布时间】:2016-10-21 07:47:36
【问题描述】:

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

@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
            }
        }
    }
}

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    使用模式。

    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
    

    【讨论】:

    • 我认为您不能设置同时接受逗号和点的模式。
    • 意思类似于50,000.25?
    • 接受逗号和点的模式=> ^[0-9.,]+$
    • True,但对于 NumberStyleFormatter,使用了 DecimalFormat.applyPattern,它不接受正则表达式。我可能需要实现一个自定义格式化程序,但仍然对 Spring 如何在不这样做的情况下实现这一点感到困惑。
    • 即使DecimalFormat.applyPattern 也提供了这样做的模式...check this
    猜你喜欢
    • 1970-01-01
    • 2018-08-31
    • 2015-03-19
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多