Spring BigDecimal 输入
Spring BigDecimal input
我有一个带有一个 BigDecimal 字段的 POJO 对象 sum.
在控制器中,我将此 POJO 对象添加为如下形式:
MyForm form = new MyForm();
model.addAttribute("command", form);
我的jsp:
<form:input path="sum" size="27"/>
在控制器中我添加了 initbinder:
binder.registerCustomEditor(BigDecimal.class, new SumEditor());
我的 SumEditor 的一部分 class:
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(parseMoney(text));
}
private BigDecimal parseMoney(String str) {
try {
return new BigDecimal(str);
} catch (Exception e) {
logger.error("error", e);
}
return null;
}
但在 JSP 视图中我看到(在输入字段中):|null________|
如何解决这个问题?我需要:|___________|
您应该简单地覆盖 SumEditor
的 getText
方法,使其 return 空字符串 ("") 为空值:
@Override
public String getAsText() {
if (getValue == null) {
return "";
}
BigDecimal val = (BigDecimal) getValue();
return val.toStr(); // or whatever conversion you need
}
我有一个带有一个 BigDecimal 字段的 POJO 对象 sum.
在控制器中,我将此 POJO 对象添加为如下形式:
MyForm form = new MyForm();
model.addAttribute("command", form);
我的jsp:
<form:input path="sum" size="27"/>
在控制器中我添加了 initbinder:
binder.registerCustomEditor(BigDecimal.class, new SumEditor());
我的 SumEditor 的一部分 class:
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(parseMoney(text));
}
private BigDecimal parseMoney(String str) {
try {
return new BigDecimal(str);
} catch (Exception e) {
logger.error("error", e);
}
return null;
}
但在 JSP 视图中我看到(在输入字段中):|null________|
如何解决这个问题?我需要:|___________|
您应该简单地覆盖 SumEditor
的 getText
方法,使其 return 空字符串 ("") 为空值:
@Override
public String getAsText() {
if (getValue == null) {
return "";
}
BigDecimal val = (BigDecimal) getValue();
return val.toStr(); // or whatever conversion you need
}