//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
最佳答案
我实现了扩展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);
}
}
}
}
并将它们插入 Controller
@InitBinder
public void initDataBinder(WebDataBinder binder) {
binder.registerCustomEditor(Double.class, new MyCustomNumberEditor(Double.class));
}
关于java - Spring @ModelAttribute 将格式化数字转换为 Double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25757623/