0
在我的驗證器中,我爲每個字段添加了一些說明,並希望以表單(.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" />
,但沒有工作...
我編輯的代碼(嘗試不同的方法),但不工作,我不明白爲什麼,請看上面的問題的編輯的代碼,有什麼問題嗎?.. – badCoder
只添加modelAndView.addObject (「storeForm」,storeForm);在您的hasErrors中,並返回您在獲取請求時顯示的相同視圖。 – tofindabhishek