我有一份注册表格:
regStore.jsp
<form:form id = "storeRegForm" method="POST" action="/regStoreSuccessful" commandName="storeForm">
<h3>Registration store</h3>
<table>
<tr>
<td><form:label path="name">Store name</form:label></td>
<td><form:input path="name" /></td>
<td><form:errors path="name" /></td>
</tr>
<tr>
<td><form:label path="storeType.id">Store type</form:label></td>
<td><form:select path="storeType.id" >
<form:options items="${typeList}" itemValue="id" itemLabel="name"/>
</form:select></td>
<td><form:errors path="storeType.id" /></td>
</tr>
<tr>
<td><form:label path="address">Store address</form:label></td>
<td><form:input path="address" /></td>
<td><form:errors path="address" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Register"/>
</td>
</tr>
</table>
并且在我的控制器中还有两种方法(GET,POST):
控制器
@RequestMapping(value = "/regStore", method = RequestMethod.GET)
public ModelAndView addStore() throws SQLException {
ModelAndView modelAndView = new ModelAndView("Store/regStore");
modelAndView.addObject("storeForm", new Store());
modelAndView.addObject("typeList", storeTypeService.getAllTypes());
return modelAndView;
}
@RequestMapping(value = "/regStoreSuccessful", method = RequestMethod.POST)
public ModelAndView addStorePost(@Valid @ModelAttribute("storeForm") Store storeForm, BindingResult bindingResult) throws SQLException {
ModelAndView modelAndView = new ModelAndView("redirect:body");
if(bindingResult.hasErrors()) {
modelAndView.addObject("storeForm", storeForm);
modelAndView.addObject("typeList", storeTypeService.getAllTypes());
return new ModelAndView("Store/regStore");
}
storeService.addStore(storeForm);
return modelAndView;
}
在我的模型中,注释,像这样:
@NotEmpty(message = "Name of store can't be empty")
private String name;
另外客户端验证:
<script type="text/javascript">
$(document).ready(function () {
$(".registration #storeRegForm").validate({
rules: {
name: "required",
address : "required"
},
messages: {
name: "Name isn't be null",
address : "Address isn't be null"
}
});
});
</script>
如果我用jQuery注释掉代码验证(客户端验证),并且我的表单字段将为空,则开始工作服务器端验证,但是在服务器端验证之后,在表单中没有显示存储类型的列表,更多显示在图像中:
谢谢!
答案 0 :(得分:1)
问题非常简单,在if
块中,您将数据填入预定义的modelAndView,然后返回不同的实例!
if(bindingResult.hasErrors()) {
modelAndView.addObject("storeForm", storeForm);
modelAndView.addObject("typeList", storeTypeService.getAllTypes());
// !!!!!!
return new ModelAndView("Store/regStore");
}