BindingResult不能獲取錯誤對象


BindingResult不能獲取錯誤對象,代碼如下:

@RequestMapping(value = "/login")
public String error4( Model model, UserModel user,BindingResult bindingResult){
    if(bindingResult.hasErrors()){
       List<ObjectError> ls=bindingResult.getAllErrors();
       System.out.println(ls);
       return "redirect:login.jsp";
    }
  return "hello";
}
public class UserModel {
    @NotNull(message="用戶名不能為空")  
    private String username;
    private String password;
       get/set……
}

總結如下:

1.  加入校驗用jar包:

2.  需要在spring配置文件中加入:  

<mvc:annotation-driven validator="validator" ></mvc:annotation-driven>
<!-- 校驗器 -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <!-- Hibernate校驗器 -->
    <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
</bean>

3.  UserModel中如果是校驗表單輸入框是否為空,應使用:

@NotEmpty(message="用戶名不能為空")  

4. BindingResult必須跟表單對象配對使用:

  如:UserModel user,BindingResult bindingResult緊隨UserModel其后

5. 需要在UserModel user前加上@Validated或者@Valid

 

歡迎補充……


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM