Spring4下validation数据校验无效(maven)

SpringMVC4使用数据校验的时候需要使用hibernate-validator的包

  • 第一步添加依赖
    <dependency>
      <groupId>javax.validationgroupId>
      <artifactId>validation-apiartifactId>
      <version>2.0.0.Finalversion>
    dependency>
    <dependency>
      <groupId>org.hibernategroupId>
      <artifactId>hibernate-validatorartifactId>
      <version>5.4.1.Finalversion>
    dependency>
  • 第二步添加校验注解
package com.demo.model;
/*
* spring4 用hibernate中的validation
* 
* */
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;

import javax.validation.constraints.Size;

public class User {
    private String username;
    private String password;
    private String nickname;
    private String email;
    public User(){

    }

    public User(String username, String password, String nickname, String email) {
        this.username = username;
        this.password = password;
        this.nickname = nickname;
        this.email = email;
    }

    @NotBlank(message = "用户名不能为空")
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Size(min = 6,max = 20,message = "密码为6-20位")
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    @Email(message = "请输入合法的邮箱")
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
  • 第三步在控制器中对指定参数进行校验注解 (注:BindingResult 必须紧跟在@Validate)
    //@Validated指定验证对象 BindingResult紧跟Validated
    @RequestMapping(value="/add",method = RequestMethod.POST)
    public String add(@Validated User user, BindingResult br){
        System.out.println(br);
        System.out.println(br.getErrorCount());
        if(br.hasErrors())
            return "user/add";
        users.put(user.getUsername(),user);
        return "redirect:/user/users";
    }
  • 注:这个配置也会影响到校验是否生效
<mvc:annotation-driven/>

你可能感兴趣的:(J2EE,SpringMVC)