2

I'm working on web application which should validate date before save it in DB. So i'm trying to use for that spring mvc validator. But I have a problem that form doesn't show error message.

My user.jsp:

<form:form class="editUser" method="POST" commandName="user">
    <form:input path="email"/>
    <form:errors path="email"/>
    other fields
</form>

My controller:

@RequestMapping(value = "/user/save", method = RequestMethod.POST)
public String save(@Valid @ModelAttribute("user") final User user,
        BindingResult result) throws Exception
{
    if (result.hasErrors()) {
        return "redirect:/addUser";
    } else {
        handler.saveUser(user);
        return "redirect:/userList";
   }
}

My User class:

public class User {
    @NotEmpty(message = "Please enter your email addresss.")
    private String email;

    other fields
}

As far as I see in debug mode result contains error if I submit empty email, but it error doesn't show on page. Could some one help me?

UPDATE: I have tried to use RedirectAttributes, but it still doesn't work.

My controller:

public String save(@Valid @ModelAttribute("user") final User user,
        BindingResult result) throws Exception
{
    if (result.hasErrors()) {
        redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.user", result);
        redirectAttributes.addFlashAttribute("errors", result.getAllErrors());
        redirectAttributes.addFlashAttribute("user", user);
        return "redirect:/addUser";
    } else {
        handler.saveUser(user);
        return "redirect:/userList";
   }
}
Vartlok
  • 2,539
  • 3
  • 32
  • 46

1 Answers1

3

Don't redirect in case of validation failed.

sample code:

public String save(@Valid @ModelAttribute("user") final User user,
        BindingResult result) throws Exception
{
    if (result.hasErrors()) {
        return "addUser";
    } else {
        handler.saveUser(user);
        return "redirect:/userList";
   }
}
Braj
  • 46,415
  • 5
  • 60
  • 76
  • 1
    But i have to, because my JSP is addUser.jsp and save method is mapped in addUser/save, so if i just use "addUser" it will be wrong behaviour. I have tried to use `RedirectAttributes`, but it doesn't work. – Vartlok Jul 31 '14 at 11:12
  • simply forward the request to the same page. – Braj Jul 31 '14 at 11:15
  • you can check this related question, it might provide an answer - perhaps your form is being reinitialised in the redirect, or using ModelAndView... http://stackoverflow.com/questions/2543797/spring-redirect-after-post-even-with-validation-errors – Richard G Feb 18 '15 at 16:43