我们在设计后端API接口的时候,对于前端传输的参数通常是要进行校验的,以保证接口能正确处理数据。
我们可以在代码中,通过if进行条件检测,然后根据检测结果来处理数据
比如这样
- if (account == null) {
- throw new Exception("用户名称不能为空");
- }
但是依赖需要验证的代码会很多很杂,写起来也不优雅,所以我们选择用validation库来帮助我们进行字段的校验。
-
-
-
org.springframework.boot -
spring-boot-starter-validation -
- @PostMapping(value = "")
- public User create(@RequestBody @Valid UserRequestBean bean) {
- return userService.create(bean);
- }
对于验证的对象通过添加注解,进行校验
- @Getter
- @Setter
- public class UserRequestBean {
-
- @NotNull(message = "用户名不能为空")
- private String username;
-
- @NotNull(message = "年龄不能为空")
- @Range(min = 18, max = 24, message = "年龄要在18-24之间")
- private Integer age;
-
- @NotNull(message = "性别不能为空")
- @Range(min = 0, max = 1, message = "性别只能是男1女0")
- private Integer gender;
-
- @NotEmpty(message = "手机号不能为空")
- @Pattern(regexp = "1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\\d{8}", message = "请输入合法的手机号")
- private String phone;
-
- private String accessCardNumber;
-
-
- }
这里用到了几个注解
NotNull 不能为null
Range 范围
NotEmpty 不能为null,也不能trim之后是length为0
Pattern 满足对应的正则表达式
SpringBoot利用ControllerAdvice注解捕获全局异常并返回统一格式数据_LO嘉嘉VE的博客-CSDN博客
这篇博客介绍了,怎么捕获异常返回统一格式的数据
捕获参数验证异常 MethodArgumentNotValidException ,并返回数据即可
- /**
- * 处理接口请求参数验证异常
- */
- @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
- @ExceptionHandler(MethodArgumentNotValidException.class)
- public ErrorResponseBean handleValidException(HttpServletRequest request, MethodArgumentNotValidException exception) {
- StringBuilder message = new StringBuilder();
- List
allErrors = exception.getBindingResult().getAllErrors(); - for (ObjectError error :
- allErrors) {
- if (message.length() > 0) {
- message.append("、");
- }
- message.append(error.getDefaultMessage());
- }
- return createErrorBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.value(), message.toString(), request);
- }
除了上面示例介绍的四个注解,还有一些常用注解如下
Null 必须为空
Min 数字最小值
Max 数字最大值
Past 必须为过去的一个日期
Future 必须为将来的一个日期
Length 字符串长度的范围
上面例子是对class对象的整体验证,如果是直接传输了一个参数,例如获取列表的搜索字段,直接进行验证,可以直接在Controller中定义规则
- @GetMapping
- public Page
list(@RequestParam @Min(value = 0, message = "页数最少为0") int page, - @RequestParam @Min(value = 1, message = "每页最少条数为1") int size,
- @RequestParam(required = false) String username,
- @RequestParam(required = false) Integer maxAge,
- @RequestParam(required = false) Integer minAge,
- @RequestParam(required = false) Integer gender,
- @RequestParam(required = false) String phone,
- @RequestParam(required = false) String accessCardNumber,
- @RequestParam(required = false) String orderParam,
- @RequestParam(required = false) String direction) {
- return userService.list(page, size, username, maxAge, minAge, gender, phone, accessCardNumber, orderParam, direction);
- }
直接使用注解定义要验证的规则就行。要注意的是,需要在这个类上添加一个注解Validated,这样参数中的注解就会生效了。
- @Validated
- @RestController
- @RequestMapping(value = "/user")
- public class UserController