在我的验证器中,我为每个字段添加了一些描述,并希望在表单(.jsp)中显示错误消息,但是当我为每个字段显示消息时,错误消息是相同的,有什么问题,我的代码:
验证
public class StoreValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Store.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.empty", "Name field is empty");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "address.empty", "Address field is empty");
}
}
控制器
@Autowired
private StoreValidator storeValidator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(storeValidator);
}
//post method create store
@RequestMapping(value = "/regStoreSuccessful", method = RequestMethod.POST)
public ModelAndView addStorePost(@Valid @ModelAttribute("storeForm") Store storeForm, BindingResult bindingResult, Principal principal, RedirectAttributes redirectAttrs) throws SQLException {
ModelAndView modelAndView = new ModelAndView("redirect:body");
storeValidator.validate(storeForm,bindingResult);
if(bindingResult.hasErrors()) {
redirectAttrs.addFlashAttribute("error", bindingResult.getFieldError().getDefaultMessage());
//modelAndView.addObject("storeForm", bindingResult.getFieldError().getDefaultMessage());
//modelAndView.addObject("storeForm", storeForm);
//redirectAttrs.addFlashAttribute("errors", bindingResult.getFieldError().getRejectedValue());
//redirectAttrs.addFlashAttribute("storeForm", storeForm);
//..
}
//..
}
表格
<form:form method="POST" action="/regStoreSuccessful" commandName="storeForm">
<table>
<tr>
<td><form:label path="name">Name store</form:label></td>
<td><form:input path="name" /></td>
<td><form:errors path="name" /></td>
</tr>
<tr>
<td><form:label path="address">Address store</form:label></td>
<td><form:input path="address" /></td>
<td><form:errors path="address" /></td>
</tr>
</form:form>
我也尝试使用<form:errors path = "name" />
,但是没有工作......
答案 0 :(得分:1)
您应该在hasErrors方法中的model属性中添加整个对象 并为每个输入单独使用表单:每个输入的错误。
<form:errors path = "name" />
<form:errors path = "address" />
if(bindingResult.hasErrors()) {
model.addAttribute("storeForm",storeForm);
//..
}