我面臨這個問題,返回ModelAndView後某些ModelAttribute值會丟失。Spring:返回ModelAndView後ModelAttribute值丟失<form:input>
例子:
這裏是所有的統計項正確填寫。我可以在調試模式下看到每個正確的值。一切似乎是罰款:
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:
@InitBinder
public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
binder.registerCustomEditor(Float.TYPE, "materialOccurences.averageM2", new StrictFloatPropertyEditor(true, true, request.getLocale()));
}
你在HTML中看到什麼?你是否得到了你期望的''標籤?路徑屬性的值是什麼? – jalynn2
您是否在''之外聲明瞭''來綁定模型屬性?另外,在你的例子中究竟是什麼'null'? –
創建的輸入標籤正確。如果我在JSP上設置值並將它們傳遞迴控制器,則會導致所有值正確到達。原因是(包括),模型屬性可用。 (見更新) –
Tunguska