Spring参数校验

1 参数校验

主要用运用:

Validator接口

注册到WebDataBinder 只支持Bean类型

1.1 配置

public class StudentValidator implements Validator{
	private static final Logger logger = LoggerFactory.getLogger(StudentValidator.class);
	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

	@Override
	public void validate(Object target, Errors errors) {
		logger.info("validate参数校验 开始....");
		ValidationUtils.rejectIfEmpty(errors, "age", "age错误");
		ValidationUtils.rejectIfEmpty(errors, "name", "name错误");
	}

}
@RestController
public class ValidatorController {
	private static final Logger logger = LoggerFactory.getLogger(ValidatorController.class);

	@InitBinder
	public void bind(WebDataBinder webDataBinder) {
		logger.info("参数校验 开始....");
		webDataBinder.addValidators(new StudentValidator());
	}
	
	@ExceptionHandler
	public Map<String,Object> exception(BindException e) {
		logger.info("异常处理 开始....");
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("ERROR", e.getAllErrors());
		return result;
	}
	
	@RequestMapping("/validator")
	public Map<String,Object> validator(@Validated Student2 student2,BindingResult errors) {
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("SUCCESS", "SUCCESS");
		return result;
	}
}

你可能感兴趣的:(spring)