【Springboot】参数校验 spring-boot-starter-validation

 # 第一步:引入依赖


    org.springframework.boot
    spring-boot-starter-validation
    xxx

# 第二步:实体类添加校验注解 

package com.holen;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Past;
import java.time.LocalDate;

public class User  {
    @NotBlank(message = "姓名不能为空")
    private String name;

    @Min(value = 1, message = "年龄不能小于1")
    private int age;

    @Email(message = "邮箱格式错误")
    private String email;

    @Past(message = "生日必须为过去的时间")
    private LocalDate birthDay;
}

# 第三步:接口添加参数校验注解  

    @PostMapping("/update")
    private void updateUser(@RequestBody @Valid User user) {
        // 修改逻辑
    }

你可能感兴趣的:(spring,boot,java,后端)