Spring 未在表单(jsp)中显示错误消息
我在表单(jsp表单)中显示错误消息时遇到问题。 我创建了一个验证器,希望看到表单中的错误(如果存在),但是没有显示错误,有什么问题 表格的一部分Spring 未在表单(jsp)中显示错误消息,spring,forms,jsp,spring-mvc,controller,Spring,Forms,Jsp,Spring Mvc,Controller,我在表单(jsp表单)中显示错误消息时遇到问题。 我创建了一个验证器,希望看到表单中的错误(如果存在),但是没有显示错误,有什么问题 表格的一部分 <form:form method="POST" action="/regStoreSuccessful" commandName="storeForm"> <table> <tr> <td><form:label path="name">Store name</form:
<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>
重定向后模型属性将不可用,您应该使用
RedirectAttributes redirectAttrs
并将错误存储为flash属性,这样重定向后属性将可用,使用后立即删除,因此将方法更改为
//post method
@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");
if(bindingResult.hasErrors()) {
redirectAttrs.addFlashAttribute("errors", bindingResult.getAllErrors());
return new ModelAndView("redirect:regStore");
}
storeService.addStore(storeForm);
return modelAndView;
}
这很有效,谢谢你)。我有一个问题,如何在没有重定向的情况下检查有效字段?np,与您的问题有关的是,您只需返回包含表单的页面视图的model和view,这样就不用使用前缀“redirect:”
@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;
}
//post method
@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");
if(bindingResult.hasErrors()) {
redirectAttrs.addFlashAttribute("errors", bindingResult.getAllErrors());
return new ModelAndView("redirect:regStore");
}
storeService.addStore(storeForm);
return modelAndView;
}