方式一:使用javax.validation和spring validation
javax.validation提供的常用注解
@NotNull: 不为NULL
@NotEmpty: 不为NULL,且不为空
@NotBlank : 不为NULL,且不为空(包括去除首尾空格)
@Max: 必须为数值,且小于等于给定值
@Min: 必须为数值,且大于等于给定值
@Email: 必须为邮箱格式
...
GET请求入参
- 在对应的参数字段上使用对应的注解(注意:如果是自定义对象接参,则需要在接参对象上使用@Valid或@Validate)
@Data public class StudentPageDTO{ @NotNull(message="parameter can not be null --- page") @Min(value=1, message="page must be over 0") private Integer page; @NotNull(message="parameter can not be null --- page") @Min(value=1, message="pageSize must be over 0") private Integer pageSize; private String name; private Integer age; }
- 在controller类上使用@Validated注解
@Validated @RestController @RequestMapping("/user") public class UserController{ /** * 基本类型 */ @GetMapping("/id") public Result getById(@NotNull(message="parameter can not be null:id") Integer id){ //to do... } /** * 自定义类型 */ @GetMapping("/page-list") public Result getPageList(StudentPageDTO dto){ //to do... } }
POST请求入参
-
参数的字段使用对应的注解
@Data public class User{ private Long id; @NotBlank(message = "parameter can not be null or empty:name") private String name; @NotNull(message = "parameter can not be null:age") @Min(value = 18,message = "age must be over 17") @Max(value = 60,message = "age can not be over 60") private Integer age; @NotBlank