验证错误时的Spring Tiles +验证

时间:2014-11-25 09:16:17

标签: spring spring-mvc spring-validator

我正在使用Tiles 3.0和Spring Validator。 如何编辑具有... / edit / {userID}等ulr的用户并且有一些验证错误,然后使用相同的url返回到该视图。我的问题是没有显示错误。 我怎样才能做到这一点? 抱歉我的英语不好!

以下是我的代码:

@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
public String getEditUser(@PathVariable int id, Model model) {

    User user = userService.getUserById(id);
    model.addAttribute("user", user);
    return "user_edit";
}

@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
public String editUser(@PathVariable int id,
        @Validated(GroupEdit.class) @ModelAttribute User user,
        BindingResult result, Model model) {

    if (result.hasErrors()){
        return "redirect:edit/" + user.getUserId();    //how can i return here?
    }
    userService.updateUser(user);
    return "redirect:edit/" + user.getUserId();
}

1 个答案:

答案 0 :(得分:0)

我发现了我的愚蠢错误。

只需返回Tile(视图),当有验证错误时从用户那里获取输入,并在该视图中修改操作表单以匹配POST方法。浏览器的URL将是../ user / {userId}。

我的观点:

<form:form action="../edit/${user.userId}" modelAttribute="user" method="post"

我的控制器:

@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
public String getEditUser(@PathVariable int id, Model model) {

    User user = userService.getUserById(id);
    model.addAttribute("user", user);
    return "user_edit";   //this is my Tiles definition in tiles.xml where user input data
}

@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
public String editUser(@PathVariable int id,
        @Validated(GroupEdit.class) @ModelAttribute User user,
        BindingResult result, Model model) {

    if (result.hasErrors()) {
        return "user_edit";   //return to the Tiles in tiles.xml, it will show error.
    }
    userService.updateUser(user);
    return "redirect:../edit/" + user.getUserId();
}