Java:Web前端入参校验

方式一:使用javax.validation和spring validation

javax.validation提供的常用注解
@NotNull: 不为NULL
@NotEmpty: 不为NULL,且不为空
@NotBlank : 不为NULL,且不为空(包括去除首尾空格)
@Max: 必须为数值,且小于等于给定值
@Min: 必须为数值,且大于等于给定值
@Email: 必须为邮箱格式
...

GET请求入参

  1. 在对应的参数字段上使用对应的注解(注意:如果是自定义对象接参,则需要在接参对象上使用@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;	
    }
    
  2. 在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请求入参

  1. 参数的字段使用对应的注解

    @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(message = "parameter can not be null or empty:email")
        @Email(message = "incorrect email format")
        private String email;
    }
    
  2. 参数使用@Valid或@Validate

    @RestController
    @RequestMapping("/user")
    public class StudentController{
    	@PostMapping("/add")
    	public Result list(@Valid @RequestBody User user){
    		//to do...
    	}
    }
    
  3. 对于同一个DTO,但不同请求需要不同校验情况的,则必须使用@Validate的分组功能,且分组依据必须是interface类型;

    @Data
    public class User{
    	/**
    	 * 使用分组功能
    	 */
    	@NotNull(group=({UserEdit.class}), message="parameter can not be null:id")
    	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(message = "parameter can not be null or empty:email")
        @Email(message = "incorrect email format")
        private String email;
    	
    	@NotEmpty(message="parameter can not be null or empty:hobby")
    	private List<@NotBlank(message="parameter can not be null or empty:hobby.str") String> hobby;
    }
    
    /**
     * validated分组接口
     */
    public interface UserEdit{}
    
    @RestController
    @RequestMapping("/user")
    public class UserController{
    
    	/**
    	 * 不会校验id
    	 */
    	@PostMapping("add")
    	public Result<Object> add(@Validated @RequestBody User user){
    		//to do...
    	}
    	
    	/**
    	 * 只校验id
    	 */
    	@PostMapping("edit")
    	public Result<Object> add(@Validated({UserEdit.class}) @RequestBody User user){
    		//to do...
    	}
    }
    
  4. 对于自定义参数中还有自定义参数的字段校验,必须在上一层的参数使用@Valid

    @Data
    public class User{
    	private Long id;
    	
    	private String name;
    
    	@Valid
    	@NotNull(message="parameter can not be null:department")
    	private Department department;
    }
    
    @Data
    public class Department{
    	@NotNull(message="parameter can not be null:department.id")
    	private Long id;
    	
    	@NotBlank(message="parameter can not be null or empty:department.name")
    	private String name;
    }
    
    @RestController
    @RequestMapping("/user")
    public class UserController{
    	@PostMapping("/add-department")
    	public Result<Object> addDepartment(@Valid @RequestBody User user){
    		//to do...
    	}
    }
    

方式二:使用Spring Assert

通过import org.springframework.util.Assert实现

Assert.notNull(): 不为NULL
Assert.hasLength(): 不为空字符串
Assert.notEmpty(): 不为空
...
@RestController
@RequestMapping("/user")
public class UserController{
	@GetMapping("/id")
	public Result getById(Integer id){
		Assert.notNull(student.getAge,"parameter can not be null:id");
		//to do...
	}
	
	@PostMapping("/add")
	public Result add(@RequestBody User user){
		Assert.hasLength(user.getName(),"parameter can not be null or empty:name");
		Assert.notNull(user.getAge(),"parameter can not be null:age");
		Assert.notEmpty(user.getHobby(),"parameter can not be null:hobby");
		for(String hobby:user.getHobby()){
			Assert.hasLength(hobby,"parameter can not be null:hobby.str");
		}
	}
}

方式三:使用自定义注解

  1. 自定义注解
    @Documented
    @Target({ElementType.METHOD,ElementType.FIELD,ElementType.ANNOTATION_TYPE,ElmentType.CONSTRUCTOR,ElementType.PARAMETER,ElementType.TYPE_USE})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validateBy=ListNotEmptyImpl.class)
    public @interface ListNotEmpty{
    	String message() default "list can not be null or empty!";
    	Class<?>[] groups() default{};
    	Class<? extends Payload>[] payload() default{};
    	
    	@Target({ElementType.METHOD,ElementType.FIELD,ElementType.ANNOATION_TYPE,ElementType.CONSTRUCTOR,ElementType.PARAMETER,ElementType.TYPE_USE})
    	@Retention(RetentionPolicy.RUNTIME)
    	@Documented
    	public @interface List{
    		ListNotEmpty[] value();
    	}
    }
    
  2. 注解实现类
    public class ListNotEmptyImpl implements ConstraintValidator<ListNotEmpty,List<?>>{
    	@Override
    	public boolean isValid(List list, ConstraintValidatorContext constraintValidatorContext){
    		boolean flag=false;
    		if(list != null){
    			for(Object obj:list){
    				if(obj == null){
    					flag=true;
    					break;
    				}
    			}
    			return !flag;
    		}
    		return false;
    	}
    }
    
  3. 自定义类
    @Data
    public class Student implements Serializable{
    	@ListNotEmpty(message="subject can not be null or empty!")
    	private List<String> subjects;
    }
    
  4. 控制类
    @RestController
    @RequestMapping("/student")
    public class StudentController{
    	@PostMapping("/customize")
    	public Result<?> customize(@RequstBody @Vaild Student student){
    		//to do
    	}
    }
    

版权声明:本文为weixin_43647393原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。