Search code examples
javaspringmodelandview

Spring @ModelAttribute Convert formatted number to Double


//Entity
public class MyEntity {
  private Double amount;
  public Double getAmount() { return this.amount; }
  public void setAmount(Double value) { this.amount = value; }
}

//Controller
@RequestMapping(value="/save")
public void save(MyEntity a) {
   //save to db
}

//
<input name="amount" value="1,252.00" />

When I summit form it's keep return 400 - Bad Request.. and I find out it's because spring unable to convert formatted number to Double. How to convert request before set into MyEntity


Solution

  • I'm implements Conversion class that extends CustomNumberEditor

    public class MyCustomNumberEditor extends CustomNumberEditor {
       public void MyCustomNumberEditor(Class numberClass, boolean allowEmpty) {
          this.numberClass = numberClass;
          this.allowEmpty = allowEmpty;
       }
    
       @Override
       public void setAsText(String text) throws IllegalArgumentException {
          if (this.allowEmpty && !StringUtils.hasText(text)) {
          // Treat empty String as null value.
          setValue(null);
          }
          else {
             try {
                setValue(Convert.to(this.numberClass, text));
             }
             catch (Exception ex) {
                throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
             }
          }
       }
    }
    

    And Insert these into controller

    @InitBinder
    public void initDataBinder(WebDataBinder binder) {
       binder.registerCustomEditor(Double.class, new MyCustomNumberEditor(Double.class));
    }