//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
..我发现它是因为spring无法将格式化的数字转换为Double。如何在设置为MyEntity
答案 0 :(得分: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));
}
答案 1 :(得分: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
方法捕捉它。