【发布时间】:2016-06-02 06:44:29
【问题描述】:
我正在尝试使用 Spring MVC 验证表单,并且它正在工作,但是当包含错误消息的视图出现时,我使用从控制器发送的对象通过 forEach 创建的字段没有被创建。
form.jsp
<form:form action="/project/product" method="POST" commandName="product">
<div>
<label>Title</label>
<input type="text" name="title">
<form:errors path="title"></form:errors>
</div>
<div>
<label>Description</label>
<textarea rows="10" cols="20" name="Description"></textarea>
<form:errors path="Description"></form:errors>
</div>
<c:forEach items="${types}" var="priceType" varStatus="status">
<div>
<label>${priceType.nome}</label>
<input type="text" name="prices[${status.index}].value">
<input type="hidden" name="prices[${status.index}].type" value=${priceType }>
</div>
</c:forEach>
<button type="submit">Save</button>
</form:form>
控制器:
@RequestMapping("/form")
public ModelAndView form(ModelMap m) {
m.addAttribute("product", new Product());
ModelAndView modelAndView = new ModelAndView("products/form");
modelAndView.addObject("types",PriceType.values());
return modelAndView;
}
@RequestMapping(method=RequestMethod.POST)
public String grava(@Valid Product product, BindingResult result, RedirectAttributes redirectAtributes, ModelMap m) {
if(result.hasErrors()) {
return "products/form";
}
productDao.save(product);
return "redirect:products/list";
}
我尝试返回 ModelAndView 而不是 String,没有成功,尝试使用“redirect:”,但随后验证消息也不起作用。
【问题讨论】:
标签: java spring validation spring-mvc