我面临的问题是,返回 ModelAndView 后某些 ModelAttribute 值会丢失。
例子:
以下是正确填写的所有统计项目。我可以在调试模式下看到每个正确的值。一切似乎都很好:
ModelAndView mav = new ModelAndView();
mav.addObject("materialStatistic", statisticsService.fillStatistic(statisticHelper));
return mav;
但是在 JSP 上,数据似乎已经丢失:(只有 NULL 值)
<c:forEach items="${materialStatistic.materialOccurences}" var="occurence" varStatus="occurenceStatus">
<td>
<form:input path="materialOccurences[${occurenceStatus.index}].averageM2" cssClass="inputFieldShort"/>
</td>
</c:forEach>
同样很奇怪的是,如果我打印出如下字段,我会收到数据:(正确的浮点值)
${occurence.averageM2}
为什么<form:input>
无法解析我的字段?
更新1:
表格声明:
<form:form modelAttribute="materialStatistic" action="" id="statistic-material-form" method="POST">
生成的代码<form:input>
<input id="materialOccurences20.averageM2" class="inputFieldShort" type="text" value="" name="materialOccurences[20].averageM2">
更新 2:
StrictFloatPropertyEditor:
this.getValue()
始终为空
public class StrictFloatPropertyEditor extends PropertyEditorSupport {
private static Log logger = LogFactory.getLog(ProposalService.class);
private Locale locale;
private boolean allowDigits;
private boolean round;
public StrictFloatPropertyEditor(boolean allowDigits, boolean round, Locale locale) {
this.allowDigits = allowDigits;
this.locale = locale;
this.round = round;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
Float parsedText = new Float(0);
try {
DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(locale);
if (formatter.getDecimalFormatSymbols().getDecimalSeparator() == ',') {
text = text.replaceAll("\\.", ",");
}
parsedText = formatter.parse(text).floatValue();
} catch (ParseException e) {
if (!text.isEmpty()) {
logger.error("Parse Exception occured. Value set to zero: " + e.getMessage());
}
}
super.setValue(parsedText);
}
@Override
public String getAsText() {
if(allowDigits){
NumberFormat nf = NumberFormat.getInstance(locale);
nf.setGroupingUsed(true);
nf.setMinimumFractionDigits(2);
String numberAsText = nf.format(this.getValue());
return numberAsText;
}else if(round){
float number = (Float) this.getValue();
Integer roundedNumber = Math.round(number);
NumberFormat nf = NumberFormat.getInstance(locale);
nf.setMinimumFractionDigits(0);
String numberAsText = nf.format(roundedNumber);
return numberAsText;
}else{
NumberFormat nf = NumberFormat.getInstance(locale);
nf.setMinimumFractionDigits(0);
String numberAsText = nf.format(this.getValue());
return numberAsText;
}
}
}
初始化绑定器:
@InitBinder
public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
binder.registerCustomEditor(Float.TYPE, "materialOccurences.averageM2", new StrictFloatPropertyEditor(true, true, request.getLocale()));
}