【发布时间】:2023-03-29 10:39:01
【问题描述】:
在我的表单(jsp 表单)中显示错误消息时遇到问题。 我创建了一个验证器,并希望在我的表单中查看错误(如果存在),但没有显示错误,这是什么问题?
部分表格
<form:form method="POST" action="/regStoreSuccessful" commandName="storeForm">
<table>
<tr>
<td><form:label path="name">Store name</form:label></td>
<td><form:input path="name" /></td>
<td><form:errors path="name" cssclass="error"/></td>
</tr>
验证器
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");
}
}
控制器
@Autowired
private StoreValidator storeValidator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(storeValidator);
}
//get method
@RequestMapping(value = "/regStore", method = RequestMethod.GET)
public ModelAndView addStore() throws SQLException {
ModelAndView modelAndView = new ModelAndView("Store/regStore", "storeForm", new Store());
}
//post method
@RequestMapping(value = "/regStoreSuccessful", method = RequestMethod.POST)
public ModelAndView addStorePost(@Valid @ModelAttribute("storeForm") Store storeForm, BindingResult bindingResult, Principal principal) throws SQLException {
ModelAndView modelAndView = new ModelAndView("redirect:body");
if(bindingResult.hasErrors()) {
modelAndView.addObject("errors", bindingResult.getAllErrors());
return new ModelAndView("redirect:regStore");
}
storeService.addStore(storeForm);
return modelAndView;
}
【问题讨论】:
标签: spring forms jsp spring-mvc controller