springboot注解校验参数

 

 

 

 

 

实例

基本应用

引入依赖

      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

 

 

Controller 中需要校验的参数Bean前添加Validated

public ResultVO updateSysUser(@RequestBody @Validated(Groups.Update.class) SysUserIPt sysUserIPt) {
        String token = request.getHeader(CommonConstant.ACCESS_TOKEN);
        SysUser userInfo = (SysUser)redisService.get(CommonConstant.PREFIX_USER_INFO+token);
        SysUser sysUser = BeanConvertor.convertBean(sysUserIPt,SysUser.class);
        try {
            int count = sysUserService.updateSysUser(sysUser,userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVO.vo(ResultCode.ERROR,e.getMessage());
        }
        SysUserIPo sysUserIPo = BeanConvertor.convertBean(sysUser, SysUserIPo.class);
        return ResultVO.vo(sysUserIPo);
    }

给参数对象添加校验注解

  /**
     * 用户ID
     */
      @NotEmpty(message = "用户id不能为空" , groups = Groups.Update.class)
        private String userId;

      /**
     * 部门ID
     */
      @NotEmpty(message = "部门ID不能为空",groups = Groups.Add.class)
      @NotEmpty(message = "部门ID不能为空",groups = Groups.Update.class)
      private String deptId;

      /**
     * 登录账号
     */
      @NotEmpty(message = "登录账号不能为空",groups = Groups.Add.class)
      @NotEmpty(message = "登录账号不能为空",groups = Groups.Update.class)
      private String loginName;

异常的统一处理

参数校验不通过时,会抛出 BingBindException 异常,可以在统一异常处理中,做统一处理。

/**
     * 方法参数错误异常
     * @param e
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class,BindException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultVO<Object> MethodArgumentNotValidExceptionHandler(Exception e) {
        log.error("参数异常");
        BindingResult bindingResult = null;
        Map map = new HashMap<>();
        if (e instanceof MethodArgumentNotValidException) {
            bindingResult = ((MethodArgumentNotValidException)e).getBindingResult();
        } else if (e instanceof BindException) {
            bindingResult = ((BindException)e).getBindingResult();
        }
        bindingResult.getFieldErrors().forEach((fieldError)->
                map.put(fieldError.getField(),fieldError.getDefaultMessage())
        );
        return ResultVO.vo( ResultCode.VALIDATE_FAILED  , map);
    }

然后加上分组校验

public class Groups {
public interface Add{}
public interface Update{}
}
就成功了
posted @ 2022-04-24 11:16  散落人间  阅读(39)  评论(0编辑  收藏  举报
interface food{} class A implements food{} class B implements food{} class C implements food{} public class StaticFactory { private StaticFactory(){} public static food getA(){ return new A(); } public static food getB(){ return new B(); } public static food getC(){ return new C(); } } class Client{ //客户端代码只需要将相应的参数传入即可得到对象 //用户不需要了解工厂类内部的逻辑。 public void get(String name){ food x = null ; if ( name.equals("A")) { x = StaticFactory.getA(); }else if ( name.equals("B")){ x = StaticFactory.getB(); }else { x = StaticFactory.getC(); } } }