博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring boot 输入参数统一校验
阅读量:5922 次
发布时间:2019-06-19

本文共 5226 字,大约阅读时间需要 17 分钟。

1 引入spring boot validate    maven 依赖

org.hibernate.validator
hibernate-validator

 

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;@ControllerAdvicepublic 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
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 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
rows = this.accountService.findAllByName(name); return ResultModel.ok(rows); }}

5 最后swagger  请求时结果:

请求参数,密码不填

响应结果:

转载于:https://www.cnblogs.com/iampkm/p/9578190.html

你可能感兴趣的文章
测试人员必学的软件快速测试方法(二)
查看>>
Agora iOS SDK-快速入门
查看>>
LeetCode | Copy List with Random Pointer
查看>>
引入间接隔离变化(三)
查看>>
统一沟通-技巧-4-让国内域名提供商“提供”SRV记录
查看>>
cocos2d-x 3.0事件机制及用户输入
查看>>
比亚迪速锐F3专用夏季座套 夏天坐垫 四季坐套
查看>>
C++ 数字转换为string类型
查看>>
程序员全国不同地区,微信(面试 招聘)群。
查看>>
【干货】界面控件DevExtreme视频教程大汇总!
查看>>
闭包 !if(){}.call()
查看>>
python MySQLdb安装和使用
查看>>
Java小细节
查看>>
poj - 1860 Currency Exchange
查看>>
chgrp命令
查看>>
Java集合框架GS Collections具体解释
查看>>
洛谷 P2486 BZOJ 2243 [SDOI2011]染色
查看>>
Spring Cloud 2.x系列之整合rocketMQ
查看>>
答疑解惑:Linux与Windows的那些事儿(2)
查看>>
百万连接之路
查看>>