0

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>
user2440712
  • 719
  • 2
  • 9
  • 16

2 Answers2

1

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");
}
M. Deinum
  • 115,695
  • 22
  • 220
  • 224
0

Can you try this

public ModelAndView editTag(@ModelAttribute("Tag") Tag tag,BindingResult result) {
 result = new BeanPropertyBindingResult(tag, "tag");
sreeprasad
  • 3,242
  • 3
  • 27
  • 33
  • I think that if you override the parameter with a new instance, the errors won't show up on the page. Try doing as @SREEPRASAD answer, but omit the instantiation line. – samuelgrigolato Aug 19 '13 at 19:00