Search code examples
springspring-mvcspring-annotations

Cannot display errors with spring <form:errors/>


I am not able to get spring validation errors displayed on the jsp page. Here is my code. On the jsp page, when I enter a empty name, the controller code does return a ModelAndView with errors, it just doesn't display it on the jsp page.

Any help would be greatly appreciated. Thank you!

@RequestMapping(value = "/editTag.htm", method = RequestMethod.POST)
public ModelAndView editTag(@ModelAttribute("Tag") Tag tag) {
    BindingResult result = new BeanPropertyBindingResult(tag, "tag");
    ValidationUtils.rejectIfEmptyOrWhitespace(result, "name", "field.required", "Tag Name is required");
    if (result.hasErrors()) {
    return new ModelAndView("tag.edit").addObject("tag",tag).addObject("errors", result);
    }

    tagDao.merge(tag);

    return new ModelAndView("redirect:/tags/listTags.htm");
}




<form:form commandName="tag">
    <form:errors path="name"/><br />
    <form:input path="name" size="30" />
    ...
</form:form>

Solution

  • You are constructing a new BindingResult whereas there is already one provided (and used in the background) by Spring. Simply adding the BindingResult to the method right after the @ModelAttribute annotated parameter gives you this. You can then get the model from the result and use that to construct a ModelAndView.

    Also observe that the ModelAttribute name (currently Tag) doesn't match the one used in the form (tag). Those 2 should match.

    Something like the following should work.

    @RequestMapping(value = "/editTag.htm", method = RequestMethod.POST)
    public ModelAndView editTag(@ModelAttribute("tag") Tag tag, BindingResult result) {
        ValidationUtils.rejectIfEmptyOrWhitespace(result, "name", "field.required", "Tag Name is required");
        if (result.hasErrors()) {
          return new ModelAndView("tag.edit", result.getModel());    
        }
    
        tagDao.merge(tag);
    
        return new ModelAndView("redirect:/tags/listTags.htm");
    }