Search code examples
javaspringdata-bindingspring-mvcnumber-formatting

Spring numberformatting with registercustomereditor on list of numbers


When registering a customerEditor in spring to format a number with a given numberFormat instance, it is easy to apply this to a specific field in the jsp, e.g.:

NumberFormat numberFormat = getNumberFormat(0, 0, 2);
PropertyEditor propertyEditor = 
    new CustomNumberEditor(Double.class, numberFormat, true);
binder.registerCustomEditor(Double.class, "myDoubleField", propertyEditor);

This will result in a correct format of the number based on the applications locale (regarding commas and dots for thousand/decimal separator) and with the specified decimals before and after the seperator.

However, if I have a list of unknown size containing doubles how can I format these in a smart way? I could of course run through the list and register one for each entry in the list, but it seems cumbersome and wrong.

Since spring is binding to lists with indicises the field names would have names like "myDoubleField[0] .... myDoubleField[n]" which therefore makes it hard...

Is there an easy workaround for this? Or is there a workaround at all?

Thanks a lot in advance, I hope someone can point me in a correct direction!


Solution

  • Solved by replacing old cumbersome way of registering custom editors, by using a global PropertyEditorRegistrar. Initializing controllers with this in constructor:

    public myController(PropertyEditorRegistrar customPropertyEditorRegistrar) {
        this.customPropertyEditorRegistrar = customPropertyEditorRegistrar;
    }
    

    and registering this in initBinder:

    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)   throws Exception {
        customPropertyEditorRegistrar.registerCustomEditors(binder);
    }
    

    Forces all elements to be formatted in the way specified in the CustomerPropertyEditorRegistrar.
    Eg. with doubles:

    public final class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {
        // Double
        PropertyEditor doubleEditor = getLocaleBasedNumberEditor(Double.class, true);
        registry.registerCustomEditor(double.class, doubleEditor);
        registry.registerCustomEditor(Double.class, doubleEditor);
    }
    

    Specific fields can the be overwritten in the old manner, if another formatting is desired for a specific field.

    //Hoof