亲宝软件园·资讯

展开

Java 校验注解

攻城狮Chova 人气:0

@Valid和@Validated

@Valid和@Validated比较

@Valid高级使用

@Valid级联校验

@Validated高级使用

@Validated分组校验

@RestController
@RequestMapping("/person")
public class PersonGroupController {
	
	// 不指定分组时校验
	@GetMapping("/person")
	public Result getPerson(@Validated @RequestBody PersonGroup person) {
		return Result.buildSuccess(person);
	}

	// 指定AddGroup分组校验
	@PostMapping("/person")
	public Result addPerson(@Validated(value = PersonGroup.AddGroup.class) @RequestBody PersonGroup person) {
		return Result.buildSuccess(person);
	}

	// 指定UpdateGroup分组校验
	@PutMapping("/person")
	public Result updatePerson(@Validated(value = PersonGroup.updateGroup.class) @RequestBody PersonGroup person) {
		return Result.buildSuccess(person);
	}
}

@Validated分组校验顺序

@Data
public class UserGroupSequence {
	
	public interface FirstGroup {}

	public interface SecondGroup {}

	// 使用GroupSequence定义分组校验顺序:按照FirstGroup,SecondGroup分组顺序进行校验
	@GroupSequence({FirstGroup.class, SecondGroup.class})
	public interface Group {}

	@NotEmpty(message = "用户ID必须提交!", group = FirstGroup.class)
	private String userId;

	@NotEmpty(message = "用户姓名必须提交!", group = FirstGroup.class)
	@Size(min = 2, max = 8, message = "用户姓名的长度在2~8之间", goup = Second.class)
	private String userName;
} 
@RestController
@RequestMapping("/user")
public class UserGroupSequenceController {
	// 这里方法中@Validated注解value的值是Group.class
	@PostMapping("/user")
	public Result addGroup(@Validated(value = Group.class) @RequestBody UserGroupSequence user) {
		return Result.buildSuccess(user);
	}
}

@Validated非实体类校验

@Validated
public class AnnotationController {
	
	@GetMapping("/person")
	public Result getAge(@Range(min = 2, max = 8, message = "年龄在3~8岁!") @RequestParam int age) {
		return Result.buildSuccess(age);
	}
}
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public Result resolveConstraintViolationException(ConstraintVilationException exception) {
	Set<ConstraintVilation<?>> constraintVilations = exception.getConstraintVilations();
	// 处理异常信息
	if (!CollectionUtils.isEmpty(constraintVilations)) {
		StringBuilder messageBuilder = new StringBuilder();
		for (ConstraintVilation constraintViolation : constraintVilations) {
			messageBuilder.append(constraintVilation.getMessage()).append(",");
		}
		String errorMessage = messageBuilder.toString();
		if (errorMessage.length() > 1) {
			errorMessage.substring(0, errorMessage.length() - 1);
		}
		return Result.builderFailure(ErrorStatus.ILLEGAL_DATA.getCode(), errorMessage);
	} 
	return Result.builderFailure(ErrorStatus.ILLEGAL_DATA.getCode(), exception.getMessage())
}

@PathVariable

正则表达式校验

// 请求路径中的id必须是数字,否则寻找不到这个路径404
@GetMapping("/user/{id:\\d+}")
public Result getId(@PathVariable(name="id") String userId) {
	return Result.buildSuccess(userId);
}

继承BasicErrorController类

@RestController
public class PathErrorController extends BasicErrorController {
	
	@Autowired
	public PathErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties, List<ErrorViewResolver> errorViewResolvers) {
		super(errorAttributes, serverProperties.getError(), errorViewResolvers);
	}

	/**
	 * 处理html请求
	 */
	@Override
	public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
		HttpStatus status = getStatus(request);
		Map<String, Object> model = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML));
		ModelAndView modelAndView = new ModelAndView("pathErrorPage", model, status);
		return modelAndView;
	}
	
	/**
	 * 处理json请求
	 */
	@Override
	public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
		Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
		
		Map<String, Object> responseBody = new HashMap<>(8);
		responseBody.put("success", false);
		responseBody.put("code", body.get("status"));
		responseBody.put("message", body.get("error")); 
		
		return new ResponseEntity<>(responseBody, HttpStatus.OK);
	}
} 

自定义校验注解

@Documented
@Constraint(validateBy = {Show.ShowConstraintValidator.class})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Rentation(RUNTIME)
public @interface Show {
	String message() default "{com.oxford.annotation.Show.message}";

	Class<?>[] groups() default {};

	Class<? extends Payload>[] payload() default {};
	
	int[] value();

	class ShowConstraintValidator implements ConstraintValidator<Show, Integer> {
		
		private Set<Integer> set = new HashSet<>();

		/**
		 * 初始化操作
		 * 获取value属性指定的数字,保存到Set集合中
		 */
		@Override
		public void initilize(Show constraintAnnotation) {
			int[] value = constraintAnnotation.value();
			for (int v : value) {
				set.add(i);
			}
		}	

		@Override
		public boolean isValid(Integer value, ConstraintValidatorContext context) {
			return set.contains(value);
		}
	} 
}
@Data
public class AnnotationQuery {
	
	@Show(value = {0, 1}, message = "数值只能是0或者1")
	private Integer isShow;
}
@PostMapping("/annotation")
public Result addAnnotation(@Validated @RequestBody AnnotationQuery annotation) {
	return Result.buildSuccess(annotation);
}

加载全部内容

相关教程
猜你喜欢
用户评论