简体   繁体   中英

Spring MVC validation doesn't show error message

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";
   }
}

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";
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM