• spring boot 输入参数统一校验


    1 引入spring boot validate    maven 依赖

     <!-- 验证 -->
            <dependency>
                <groupId>org.hibernate.validator</groupId>
                <artifactId>hibernate-validator</artifactId>
            </dependency>

    2  输入参数 模型 dto

    package com.example.demo.input;
    
    import javax.validation.constraints.NotEmpty;
    import javax.validation.constraints.Size;
    
    public class AccountCreateInput {
    
        @Size(min=6, max=30,message = "账号名长度必须在6,30之间")
        private String loginName ;
        @NotEmpty(message = "密码不能为空")
        private String loginPwd;
        private String realName;
    
        public String getLoginName() {
            return loginName;
        }
    
        public void setLoginName(String loginName) {
            this.loginName = loginName;
        }
    
        public String getLoginPwd() {
            return loginPwd;
        }
    
        public void setLoginPwd(String loginPwd) {
            this.loginPwd = loginPwd;
        }
    
        public String getRealName() {
            return realName;
        }
    
        public void setRealName(String realName) {
            this.realName = realName;
        }
    }
    

    3 启用统一验证错误处理 。 当参数模型验证未通过,会抛出

    MethodArgumentNotValidException  异常,统一处理即可。 
    package com.example.demo.config;
    
    import com.example.demo.Infrastructure.FriendlyException;
    import com.example.demo.Infrastructure.UnauthorizedException;
    import com.example.demo.Infrastructure.http.ResultModel;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.FieldError;
    import org.springframework.web.bind.MethodArgumentNotValidException;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import javax.servlet.http.HttpServletRequest;
    
    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        private Logger logger = LoggerFactory.getLogger(this.getClass());
    
        @ExceptionHandler(value = Exception.class)
        @ResponseBody
        public ResultModel jsonErrorHandler(HttpServletRequest req, Exception e) {
    
            // 友好提示错误
            if (e instanceof FriendlyException) {
                logger.info(e.getMessage());
                return ResultModel.internalServerError(e.getMessage());
            }
            // 权限校验
            else if (e instanceof UnauthorizedException) {
                logger.info(e.getMessage());
                return ResultModel.Unauthorized(e.getMessage());
    
            }
            // 全局统一校验
            else if(e instanceof MethodArgumentNotValidException ){
                MethodArgumentNotValidException  ex = (MethodArgumentNotValidException ) e;
    
                BindingResult result = ex.getBindingResult();
                StringBuffer sb = new StringBuffer();
    
                for (FieldError error : result.getFieldErrors()) {
                    String field = error.getField();
                    String msg = error.getDefaultMessage();
                    String message = String.format("%s:%s ", field, msg);
                    sb.append(message);
                }
    
                return ResultModel.internalServerError(sb.toString());
            }
            // 未知异常
            else {
                logger.error(e.getMessage(), e);
                return ResultModel.internalServerError(e.toString());
            }
        }
    
    }
    

    4  在controller 中标注需要验证的输入参数,在CreateAccountInput 参数前,添加@validated 注解

    package com.example.demo.controller;
    
    import com.example.demo.Infrastructure.http.ResultModel;
    import com.example.demo.domain.Account;
    import com.example.demo.input.AccountCreateInput;
    import com.example.demo.service.IAccountService;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import io.swagger.annotations.ApiParam;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.*;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.util.List;
    
    @Api(value = "Account api", description = "api of account")
    @RestController
    @RequestMapping("/account")
    public class AccountController {
    
        private Logger logger = LoggerFactory.getLogger(this.getClass());
    
        @Autowired
        IAccountService accountService;
    
        @ApiOperation(value = "account index list", notes = "账户列表信息")
        @RequestMapping(value = "/index", method = RequestMethod.GET)
        public ResultModel index() {
    
            List<Account> rows = this.accountService.findAll();
            return ResultModel.ok(rows);
        }
    
        @ApiOperation(value = "create a account", notes = "a account name")
    
        @RequestMapping(value = "/create", method = RequestMethod.POST)
        public ResultModel create(
                @ApiParam(name = "model", value = "input a account entity") @RequestBody @Validated AccountCreateInput model)  {
    
            this.accountService.Create(model);
            Account entity = this.accountService.findAccountByName(model.getLoginName());
            return ResultModel.ok(entity);
        }
    
        @ApiOperation(value = "find account by name", notes = "根据登录名查找账户")
        @RequestMapping(value = "/query", method = RequestMethod.GET)
        public ResultModel query(@RequestParam String name)  {
            this.logger.info(String.format("url:/account/query?name=%s ",name));
    
            List<Account> rows = this.accountService.findAllByName(name);
            return ResultModel.ok(rows);
    
        }
    }
    

    5 最后swagger  请求时结果:

    请求参数,密码不填

    image

    响应结果:

    image

  • 相关阅读:
    go 自定义RWMutex
    go defer的*i和i参数
    go defer 易错题
    EasyPlayer移动端播放webrtc协议时长按播放页面无法关闭“关于我们”页面
    高速公路服务区智能一体机解决方案
    【操作教程】TSINGSEE青犀视频平台如何将旧数据库导入到新数据库?
    EasyPlayer流媒体播放器播放HLS视频,起播速度慢的技术优化
    开发那些事儿:如何在CentOS7下安装部署ffmpeg?
    开发那些事儿:前端开发环境报错“[vuex]unknown action type”如何解决?
    H.264转码H.265出现崩溃并报错“missing picture”该如何解决?
  • 原文地址:https://www.cnblogs.com/iampkm/p/9578190.html
Copyright © 2020-2023  润新知