源码下载
ChaiRongD/Demooo - Gitee.com
注意依赖和注解到底是引用的哪个包
请求参数验证
请求参数不为null
首先定义一个dto
package com.example.springbootparamvalidatedemo.dto; import lombok.Data; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; @Data public class StudentDto { @NotNull(message = "id不能为空") private Integer id; @NotBlank(message = "name不能为空") private String name; @NotBlank(message = "email不能为空") private String email; }
写一个测试接口
@PostMapping("/studentHello") public StudentDto studentHello(@Validated @RequestBody StudentDto student) { return student; }
当请求体为下面时(少name字段),会报错,就不贴错误了
{"id":1, "email":"email" }
分组验证
比如经常会有添加和修改某类的需求,其实请求里就是一个字段ID是否需要验证,其实这里是可以复用的,如果我能告诉系统 这个是插入操作,不需要验证ID,这个是修改操作,必须要验证ID,那就爽歪歪了,不过确实有这种骚操作。
首先定义两个接口标志
public class BaseConstant { public static interface Insert {} public static interface Update {} }
下面定义dto对象,分别标记什么操作下验证什么字段
public class TeacherDto { @NotNull( message = "id不能为空", groups = {BaseConstant.Update.class}) private Integer id; @NotBlank( message = "name不能为空", groups = {BaseConstant.Update.class, BaseConstant.Insert.class}) private String name; @NotBlank( message = "email不能为空", groups = {BaseConstant.Update.class, BaseConstant.Insert.class}) private String email; }
下面定义的是接口,其中注意接口的参数前面的注解,这样就能实现根据某个类型判断不同的字段 ,亲测可用,不贴结果了
@PostMapping("/insertTeacherHello") public TeacherDto insertTeacherHello( @Validated(BaseConstant.Insert.class) @RequestBody TeacherDto teacherDto) { return teacherDto; } @PostMapping("/updateTeacherHello") public TeacherDto updateTeacherHello( @Validated(BaseConstant.Update.class) @RequestBody TeacherDto teacherDto) { return teacherDto; }
但是也有一种情况,就是下面这中,我不指定Validated注解里的参数,那结果就是不做任何校验。
@PostMapping("/teacherHello") public TeacherDto teacherHello(@Validated @RequestBody TeacherDto teacherDto) { return teacherDto; }
全局异常捕捉返回友好提示
上面只能保证接口不会访问到,但是你要返回一个友好的提示,那就需要全局异常捕捉。
@ControllerAdvice public class AllException { @ExceptionHandler(value = Exception.class) @ResponseBody public String exception(Exception e) { return "exception处理错误!" + e.getMessage(); } // 请求接口参数错误会走下面这个方法 @ExceptionHandler(value = BindException.class) @ResponseBody public String BindException(BindException e) { BindingResult bindingResult = e.getBindingResult(); String errorMesssage = ""; for (FieldError fieldError : bindingResult.getFieldErrors()) { errorMesssage += fieldError.getDefaultMessage() + "!"; } return "BindException处理错误!" + errorMesssage; } }