spring boot校验参数
导入依赖
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
接口中添加注解@Valid
@PostMapping("add")
@ResponseBody
public Result add(@RequestBody @Valid UserAddRequest userAddRequest) {
return ResultEnum.SUCCESS.toRet();
}
实体类注解
import lombok.Data;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
@Data
public class UserAddRequest {
@NotBlank(message = "用户名不能为空")
private String username;
@Max(value = 3, message = "年龄不合法")
@Min(value = 1, message = "年龄不合法")
private int sex;
}