1 引入spring boot validate maven 依赖
<!-- 验证 -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
|
2 输入参数 模型 dto
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
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;
}
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
|
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());
}
}
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
|
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);
}
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
|
5 最后swagger 请求时结果:
请求参数,密码不填

响应结果:

- spring boot validation参数校验
对于任何一个应用而言在客户端做的数据有效性验证都不是安全有效的,这时候就要求我们在开发的时候在服务端也对数据的有效性进行验证. Spring Boot自身对数据在服务端的校验有一个比较好的支持,它能将 ...
- Kotlin + Spring Boot 请求参数验证
编写 Web 应用程序的时候,经常要做的事就是要对前端传回的数据进行简单的验证,比如是否非空.字符长度是否满足要求,邮箱格式是否正确等等.在 Spring Boot 中,可以使用 Bean Valid ...
- Spring boot 配置文件参数映射到配置类属性
[参考文章]:SpringBoot之@EnableConfigurationProperties分析 [参考文章]:在Spring Boot中使用 @ConfigurationProperties 注 ...
- spring Boot使用AOP统一处理Web请求日志记录
1.使用spring boot实现一个拦截器 1.引入依赖: <dependency> <groupId>org.springframework.boot</grou ...
- 前端参数统一校验工具类ValidParamUtils
1,前端参数不可信,对于后端开发人员来说应该是一条铁律,所以对于前端参数的校验,必不可少,而统一的前端参数校验工具,对我们进行参数校验起到事半功倍的效果 2,统一参数校验工具ValidParamUti ...
- spring boot 2 全局统一返回RESTful风格数据、统一异常处理
全局统一返回RESTful风格数据,主要是实现ResponseBodyAdvice接口的方法,对返回值在输出之前进行修改.使用注解@RestControllerAdvice拦截异常并统一处理. 开发环 ...
- Spring Boot 构造器参数绑定,越来越强大了!
在之前的文章:Spring Boot读取配置的几种方式,我介绍到 Spring Boot 中基于 Java Bean 的参数绑定,在一个 Java Bean 类上用 @ConfigurationPro ...
- spring boot 拦截异常 统一处理
spring boot 默认情况下会映射到 /error 进行异常处理,提示不友好,需要自定义异常处理,提供友好展示 1.自定义异常类(spring 对于 RuntimeException 异常才会进 ...
- spring boot datasource 参数设置
datasource spring.dao.exceptiontranslation.enabled是否开启PersistenceExceptionTranslationPostProcessor,默 ...
随机推荐
- HDU P2222 Keywords Search
In the modern time, Search engine came into the life of everybody like Google, Baidu, etc.Wiskey als ...
- git 之奇技淫巧
1,git remote prune origin 本地有很多其实早就被删除的远程分支,可以用 git remote prune origin 全部清除掉,这样再 checkout 别的分支时就清晰 ...
- QQ 聊天机器人小薇 2.1.0 发布!
本次发布加入了支持茉莉机器人,并且更容易搭建开发环境,在线显示登录二维码~ 简介 XiaoV(小薇)是一个用 Java 写的 QQ 聊天机器人 Web 服务,可以用于社群互动: 监听多个 QQ 群消息 ...
- 微服务&spring cloud架构系列汇总
为了方便查找,把微服务&微服务架构之spring cloud架构系列文章按时间正序整理了一下,记录如下: 1. 微服务架构之spring cloud 介绍 2. 微服务架构之spring ...
- linux shell实现守护进程 看门狗 脚本
嵌入式初学者,第一次上传代码.昨天做了一个udhcpd与udhcpc的守护,目前只会用shell模仿编写,还有什么方法可以做守护呢? ? 1 2 3 4 5 6 7 8 9 10 11 12 13 1 ...
- Angular1.x directive(指令里的)的compile,pre-link,post-link,link,transclude
The nitty-gritty of compile and link functions inside AngularJS directives The nitty-gritty of comp ...
- 基于Vue的WebApp项目开发(五)
实现图片分享列表 步骤一:新增图片列表文件photolist.vue <template> <div id="tml"> 图片分享页面 </div&g ...
- Linux修改Oracle用戶
Linux下SSH登陆后: su - Oracle; sqlplus /nolog; conn system/密码; 或者 connect/as sysdba; alter user 用户名 iden ...
- Xshell启动时显示丢失MSVCP110.dll
重装系统,装完Xshell5启动时,出现丢失MSVCP110.dll文件 这种情况不要相信网上所说的什么下载“MSVCP110.dll”文件或者下载微软的vcredist 2012 这样没用 正确的姿 ...
- Server runtime
spring mvc常用的注解: 个介绍. @Controller @Controller 负责注册一个bean 到spring 上下文中,bean 的ID 默认为 类名称开头字母小写,你也可以自己指 ...