当前位置:   article > 正文

Java:Web前端入参校验_java web 入参实体进行校验,同时校验实体里面的集合里面的实体

java web 入参实体进行校验,同时校验实体里面的集合里面的实体

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

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

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;	
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
  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...
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
  2. 参数使用@Valid或@Validate

    @RestController
    @RequestMapping("/user")
    public class StudentController{
    	@PostMapping("/add")
    	public Result list(@Valid @RequestBody User user){
    		//to do...
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    /**
     * validated分组接口
     */
    public interface UserEdit{}
    
    • 1
    • 2
    • 3
    • 4
    @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...
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
  4. 对于自定义参数中还有自定义参数的字段校验,必须在上一层的参数使用@Valid

    @Data
    public class User{
    	private Long id;
    	
    	private String name;
    
    	@Valid
    	@NotNull(message="parameter can not be null:department")
    	private Department department;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    @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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    @RestController
    @RequestMapping("/user")
    public class UserController{
    	@PostMapping("/add-department")
    	public Result<Object> addDepartment(@Valid @RequestBody User user){
    		//to do...
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

方式二:使用Spring Assert

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

Assert.notNull(): 不为NULL
Assert.hasLength(): 不为空字符串
Assert.notEmpty(): 不为空
...
  • 1
  • 2
  • 3
  • 4
@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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

方式三:使用自定义注解

  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();
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
  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;
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
  3. 自定义类
    @Data
    public class Student implements Serializable{
    	@ListNotEmpty(message="subject can not be null or empty!")
    	private List<String> subjects;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
  4. 控制类
    @RestController
    @RequestMapping("/student")
    public class StudentController{
    	@PostMapping("/customize")
    	public Result<?> customize(@RequstBody @Vaild Student student){
    		//to do
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/310817
推荐阅读
相关标签
  

闽ICP备14008679号