Spring MVC:@RequestParam验证

时间:2011-04-04 08:14:36

标签: validation spring-mvc

在我的注册表单中,我使用Bean Validator(JSR-303)来验证User对象,并且需要单独验证密码确认,因为它不是User的成员。我在为confirm字段分配错误消息时遇到问题。怎么做?

查看:

<form:form modelAttribute="user" method="post" action="register.html">
        <div class="fcell">
            <div class="clabel"><spring:message code="label.password"/></div>
            <div class="cdata"><form:password path="password"/></div>
            <div class="cmsgs"><form:errors path="password" /></div>
        </div>
        <div class="fcell">
            <div class="clabel"><spring:message code="label.confirm"/></div>
            <div class="cdata"><input type="password" name="confirm"/></div>
            <div class="cmsgs"></div>
        </div>
</form:form>

控制器:

@RequestMapping("/register.html")
public String register(@RequestParam("confirm") String confirm, @ModelAttribute("user") @Valid User user, BindingResult result) {
    if(!DigestUtils.sha256Hex(confirm).equals(user.getPassword())) {
           /* Invalid property 'confirm' ... */                   
           result.rejectValue("confirm", "text.passwords_not_equal");
    }
    return "register";
}

1 个答案:

答案 0 :(得分:2)

在这种情况下,确认可以被视为模型对象的一部分,如下所示:

public class RegistrationForm {
    @Valid
    private User user;
    private String confirm;
    ...
}

...

public String register(@ModelAttribute("user") @Valid RegistrationForm user,
   BindingResult result) { ... }   

... 

<div class="cdata">
    <form:password path="confirm"/></div>
    <div class="cmsgs"><form:errors path="confirm" />
</div>  
...