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

当我登顶时,它一直返回400 - Bad Request..我发现这是因为弹簧无法将格式化的数字转换为双精度数。如何将设置前的请求转换为MyEntity

4

2 回答 2

1

我正在实现扩展的转换类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);
         }
      }
   }
}

并将这些插入控制器

@InitBinder
public void initDataBinder(WebDataBinder binder) {
   binder.registerCustomEditor(Double.class, new MyCustomNumberEditor(Double.class));
}
于 2014-09-10T06:39:50.590 回答
0

尝试以下操作:

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

由于您没有发送整个模型属性,而只是一个值,因此这应该适合您。

或者,您可以@ModelAttrubute在弹簧形式中指定并在save方法上捕获它。

于 2014-09-10T05:07:32.763 回答