测试开发进阶——spring boot——MVC——Spring MVC框架的数据验证——校验框架 @Valid 和 @Validated的使用
/** * 多个对象校验 * @param user * @param bindingResult */ @RequestMapping("/user/saveAll") public void saveAll(@Validated User user, BindingResult bindingResult,@Validated Student student, BindingResult bindingResult2) { if (bindingResult.hasErrors()) { for (ObjectError error : bindingResult.getAllErrors()) { System.out.println(error.getDefaultMessage()); } } System.out.println("-----------"); if (bindingResult2.hasErrors()) { for (ObjectError error : bindingResult2.getAllErrors()) { System.out.println(error.getDefaultMessage()); } } }
@Validated //第1步,告诉MethodValidationPostProcessor此Bean需要开启方法级别验证支持 @RestController public class ValidationController { @RequestMapping(value = "/validation/demo") public void demo1( @Range(min = 1, max = 9, message = "年级只能从1-9") //第2步 @RequestParam(name = "grade", required = true) int grade, // @Min(value = 1, message = "班级最小只能1") @Max(value = 99, message = "班级最大只能99") //第2步 @RequestParam(name = "classroom", required = true) int classroom) { // System.out.println(grade + "," + classroom); } }
测试:
package com.awaimai.web; import org.hibernate.validator.constraints.Range; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; import javax.validation.constraints.Max; import javax.validation.constraints.Min; @Controller @Validated public class kzq { @RequestMapping(value = "/test8") @ResponseBody public String test8(@RequestParam(name = "a", required = true) @Range(min = 1, max = 9, message = "年级只能从1-9") int a,
@Min(value = 1, message = "班级最小只能1") @Max(value = 99, message = "班级最大只能99") int b) { System.out.println(a + "," + b); return "123"; } }
执行:
下面提供一种全局的异常信息捕获方法:
使用 @ControllerAdvice
注解,具本如下:
@ControllerAdvice @Component public class GlobalExceptionHandler { /** * 拦截捕捉 MissingServletRequestParameterException 异常 */ @ResponseBody @ExceptionHandler(value = MissingServletRequestParameterException.class) public String doMissingServletRequestParameterHandler(MissingServletRequestParameterException exception) { MissingServletRequestParameterException exs = (MissingServletRequestParameterException) exception; System.err.println(exs.getMessage()); return "bad request, "; } /** * 拦截捕捉 ConstraintViolationException 异常 */ @ResponseBody @ExceptionHandler(value = ConstraintViolationException.class) public Map ConstraintViolationExceptionHandler(ConstraintViolationException ex) { Map map = new HashMap(); Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations(); Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator(); List<String> msgList = new ArrayList<>(); while (iterator.hasNext()) { ConstraintViolation<?> cvl = iterator.next(); System.err.println(cvl.getMessageTemplate()); msgList.add(cvl.getMessageTemplate()); } map.put("status", 500); map.put("msg", msgList); return map; } /** * 拦截捕捉 MethodArgumentNotValidException 异常 */ @ExceptionHandler(MethodArgumentNotValidException.class) public Map doMethodArgumentNotValidException2(MethodArgumentNotValidException ex){ Map map = new HashMap(); map.put("status", 500); map.put("msg", "请求异常"); BindingResult result = ex.getBindingResult(); List<String> msgList = new ArrayList<String>(); if (result.hasErrors()) { List<ObjectError> errors = result.getAllErrors(); ObjectError error=errors.get(0); msgList.add(error.getDefaultMessage()); String firstMsg=msgList.get(0); map.put("msg", msgList); return map ; } return map ; } /** * 拦截捕捉 BindException 异常 */ @ExceptionHandler(BindException.class) @ResponseBody public R handleBindException(BindException ex) { List<FieldError> bindingResult = ex.getBindingResult().getFieldErrors(); List<String> msgList = new ArrayList<String>(); for (FieldError fieldError : bindingResult) { System.err.println(fieldError.getField() + " " + fieldError.getDefaultMessage()); msgList.add(fieldError.getDefaultMessage()); } String firstMsg = msgList.get(0); return R.error(firstMsg); } }