2011-04-04 179 views
1

在我的註冊表格中,我使用Bean Validator(JSR-303)驗證User對象,並且需要單獨驗證密碼確認,因爲它不是User的成員。我有一個問題,爲confirm字段分配錯誤消息。怎麼做 ?Spring MVC:@RequestParam驗證

查看:

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

回答

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> 
... 
+0

非常感謝! :) – marioosh 2011-04-04 09:04:29