在Spring MVC中,我想在同一页面中创建多个表单。据我说,这在逻辑上是正确的。但它给出了错误
错误:org.springframework.web.servlet.tags.form.HiddenInputTag - BindingResult和bean名称'cost'的普通目标对象都不是 可用作请求属性
控制器
@RequestMapping(value = { "/vehicle_cost" }, method = RequestMethod.GET)
public String vehicleCost(Model model, @RequestParam(defaultValue="0") int vId) {
List<CostModel> _costs = null;
List<CurrencyModel> _currencies = accountingService.getCurrencyList();
List<IdElemModel> _cost_per_types = accountingService.getCostPerTypeList();
if(vId > 0){
_costs = operationService.getVehicleCostsByVehicleId(vId);
}
else{
}
model.addAttribute("costs", _costs);
model.addAttribute("currencies",_currencies);
model.addAttribute("cost_per_types",_cost_per_types);
return "vehicle_management/vehicle_cost";
}
查看
<c:forEach items="${costs}" var="cost">
<form:form commandName="cost" method="POST" action="save_vehicle_cost" cssClass="form-horizontal" role="form">
<form:hidden path="costId" />
<form:hidden path="costCategoryId" />
<div class="form-group">
<div class="col-lg-2">
<form:input path="cost" cssClass="form-control" />
</div>
<div class="col-lg-1">
<form:input path="taxRatio" cssClass="form-control" />
</div>
<div class="col-xs-2">
<form:select path="currencyId" cssClass="form-control">
<option value="-1">Currency</option>
<form:options items="${currencies}" itemLabel="currency"
itemValue="currencyId" />
<form:options/>
</form:select>
</div>
<div class="col-lg-2">
<form:select path="costPerTypeId" cssClass="form-control">
<option value="-1">Per Type</option>
<form:options items="${cost_per_types}" itemLabel="elem"
itemValue="id" />
<form:options/>
</form:select>
</div>
<div class="col-lg-2">
<form:input path="periodBegin" cssClass="form-control dateInput" />
</div>
<div class="col-lg-2">
<form:input path="periodEnd" cssClass="form-control dateInput" />
</div>
<div class="col-lg-1"><button type="submit" class="btn btn-success">SAVE</button>
</div>
</div>
</form:form>
</c:forEach>
答案 0 :(得分:0)
表单期望“cost”在请求中,但是您的循环不会将对象放在正确的范围内。按照标准的Spring MVC模式在控制器中预先填充命令对象,您只需预加载它们:
在您的控制器中,将每个成本对象放入正确的范围,方法是使用“cost_”+ id:
等键加载它们for(CostModel c: _costs) {
model.addAttribute("cost_" + c.getId(), c);
}
在渲染表单时,在jsp中,在请求范围中查找“cost _ $ {id}”:
<c:forEach items="${costs}" var="cost">
<form:form commandName="cost_${cost.id}" method="POST" action="save_vehicle_cost" cssClass="form-horizontal" role="form">
...
...
</c:forEach>
我希望有所帮助。