未在表单中显示错误消息(jsp)

时间:2015-01-14 11:12:22

标签: 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: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;
}

1 个答案:

答案 0 :(得分:1)

重定向后模型属性不可用,您应该使用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;
}