SpringMVC: @Valid 表单验证

使用例子

  • Spring Boot 提供了强大的表单验证功能实现

假设我们有一个 Student 实体类

@Entity
@Table(name = "Student")
@Data
public class Student {
    @Id
    @GeneratedValue
    private Integer id;

    @NotEmpty(message = "姓名不能为空!")
    @Column(length = 50)
    private String name;

    @NotNull(message = "年龄不能为空!")
    @Min(value = 18, message = "年龄必须大于18岁!")
    @Column(length = 50)
    private Integer age;
}

Dao 接口

public interface StudentRepository extends JpaRepository<Student,Integer> {}
      ○ Service 接口:
public interface StudentService {
    void add(Student student);
}

Service 接口实现类

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

    @Override
    public void add(Student student) {
        studentRepository.save(student);
    }
}

Controller

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @PostMapping(value="/add")
    public String add(@Valid Student student, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return bindingResult.getFieldError().getDefaultMessage();
        }else{
            studentService.add(student);
            return "添加成功!";
        }
    }
}
  • @ValidBindingResult
    • @Valid 注解在参数上,表示让 Spring 验证该参数的属性
    • @Valid 参数后紧跟着一个 BindingResult 参数,用于获取校验结果,否则 Spring 会在校验不通过时抛出异常

校验注解

空检查

  • @Null:限制只能为 null
  • @NotNull:限制不能为 null
  • @NotEmpty:不为 null 且不为空(字符串长度不为0、集合大小不为0)
  • @NotBlank:不为空(不为 null、去除首位空格后的长度为0,与@NotEmpty不同的是字符串比较时会去除字符串的空格)

Boolean检查

  • @AssertFalse:限制必须为false
  • @AssertTrue:限制必须为true

长度检查

  • @Size(max,min):限制长度必须在 min 到 max 之间
  • @Length(min=,max=):长度在 min 到 max 之间

日期检查

  • @Past:验证注解的元素值(日期类型)比当前时间早
  • @Future:限制必须为一个将来的日期
  • @Pattern(value):限制必须符合制定的正则表达式

数值检查

  • @Max(value):限制必须为一个大于指定值的数字
  • @Min(value):限制必须为一个小于指定值的数字
  • @DecimalMax(value):限制必须为一个大于指定值的数字
  • @DecimalMin(value):限制必须为一个小于指定值的数字
  • @Range(min=, max=) :数值在 min 到 max 之间
  • @Digits(integer,fraction):限制必须为一个小数,整数部分位数不能超过integer,小数部分不能超过 fraction

其它检查

  • @Email:验证元素的值时Email
  • @URL(protocol=,host=, port=,regexp=, flags=):请求地址、端口、主机检查



作者:林塬
链接:https://www.jianshu.com/p/f85c248294f6
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

猜你喜欢

转载自blog.csdn.net/weixin_42608550/article/details/82980044