0
//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

Bear0x3f
  • 142
  • 1
  • 16

2 Answers2

1

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));
}
Bear0x3f
  • 142
  • 1
  • 16
0

Try following:

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(HttpServletRequest request) {
   Double doubleVal=Double.parseDouble(request.getParameter("amount"));
   MyEntity myEnt=new MyEntity();
   myEnt.setAmount(doubleVal);
   //save to db
}

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

As you are not sending the whole model attribute but just a value, this should work for you.

Alternatively you can specify @ModelAttrubute in your spring form and catch it on save method.

Darshan Lila
  • 5,772
  • 2
  • 24
  • 34
  • There's no Spring solution? `@Converter` or `@Binder`, `MyEntity` may be have many properties. – Bear0x3f Sep 10 '14 at 05:45
  • @BooBooBear [this](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html) might help you. – Ankur Singhal Sep 10 '14 at 06:23