一、添加依赖

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

二、实体类中添加校验规则注解

package cn.bounter.validation.entity;

import lombok.Data;
import lombok.experimental.Accessors; import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank; @Data
@Accessors(chain = true)
public class Bounter { @NotBlank
private String name; @Min(18)
private Integer age; }

JSR-303常用注解如下:

//空检查
@NotNull          对象不为null
@NotBlank         字符串不为null且不是”“ 
@NotEmpty         集合不为null且不为空
 
//长度检查
@Size(min = 1, max = 10)     字符串长度或集合大小
@Length                      字符串长度   
 
//数值检查
@Min(1)
@Max(10)
@Range(min = 1, max = 10)
 
//其他
@Email
@AssertTrue
@AssertFalse 
 
 
三、开启校验(开启后请求时会自动触发校验,校验失败抛出异常)
package cn.bounter.validation.controller;

import cn.bounter.validation.common.ResponseData;
import cn.bounter.validation.entity.Bounter;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; @RestController
@RequestMapping("/api/bounter")
public class BounterController { @PostMapping
public ResponseData<?> post(@Validated Bounter bounter) {
return ResponseData.ok(bounter);
} @PostMapping("/json")
public ResponseData<?> postJson(@Validated @RequestBody Bounter bounter) {
return ResponseData.ok(bounter);
} @GetMapping
public ResponseData<?> get(@Validated Bounter bounter) {
return ResponseData.ok(bounter);
} }

四、统一处理校验异常,并返回错误提示

package cn.bounter.validation.common;

import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.stream.Collectors; @RestControllerAdvice
public class AppExceptionHandler { /**
* 处理不带任何注解的参数绑定校验异常
* @param e
* @return
*/
@ExceptionHandler(BindException.class)
public ResponseData<?> handleBingException(BindException e) {
String errorMsg = e.getBindingResult().getAllErrors()
.stream()
.map(objectError -> ((FieldError)objectError).getField() + ((FieldError)objectError).getDefaultMessage())
.collect(Collectors.joining(","));
//"errorMsg": "name不能为空,age最小不能小于18"
return new ResponseData<>().fail(errorMsg);
} /**
* 处理 @RequestBody参数校验异常
* @param e
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseData<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
String errorMsg = e.getBindingResult().getAllErrors()
.stream()
.map(objectError -> ((FieldError)objectError).getField() + ((FieldError)objectError).getDefaultMessage())
.collect(Collectors.joining(","));
//"errorMsg": "name不能为空,age最小不能小于18"
return new ResponseData<>().fail(errorMsg);
} }

五、如需要手动触发校验,则可使用下面的方式

package cn.bounter.validation;

import cn.bounter.validation.entity.Bounter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set; @RunWith(SpringRunner.class)
@SpringBootTest
public class BounterValidationApplicationTests { //参数校验器
@Autowired
private Validator validator; /**
* 测试手动触发校验
*/
@Test
public void testValidation() {
Bounter bounter = new Bounter().setName("").setAge(17); Set<ConstraintViolation<Bounter>> violationSet = validator.validate(bounter);
violationSet.forEach(violation -> {
//name不能为空
//age最小不能小于18
System.out.println(violation.getPropertyPath() + violation.getMessage());
});
} }

这就是全部的步骤了,是不是觉得的挺简单的哉!那就赶快自己动手试试吧!

Github传送门:https://github.com/13babybear/bounter-validation

SpringBoot 参数校验的更多相关文章

  1. 补习系列(4)-springboot 参数校验详解

    目录 目标 一.PathVariable 校验 二.方法参数校验 三.表单对象校验 四.RequestBody 校验 五.自定义校验规则 六.异常拦截器 参考文档 目标 对于几种常见的入参方式,了解如 ...

  2. springboot 参数校验详解

    https://www.jianshu.com/p/89a675b7c900 在日常开发写rest接口时,接口参数校验这一部分是必须的,但是如果全部用代码去做,显得十分麻烦,spring也提供了这部分 ...

  3. SpringBoot 参数校验的方法

    Introduction 有参数传递的地方都少不了参数校验.在web开发中,前端的参数校验是为了用户体验,后端的参数校验是为了安全.试想一下,如果在controller层中没有经过任何校验的参数通过s ...

  4. springmvc、springboot 参数校验

    参数校验在项目中是必不可少的,不仅前端需要校验,为了程序的可靠性,后端也需要对参数进行有效性的校验.下面将介绍在springmvc或springboot项目中参数校验的方法 准备工作: 引入校验需要用 ...

  5. springboot参数校验

    为了能够进行嵌套验证,必须手动在Item实体的props字段上明确指出这个字段里面的实体也要进行验证.由于@Validated不能用在成员属性(字段)上,但是@Valid能加在成员属性(字段)上,而且 ...

  6. springboot学习-jdbc操作数据库--yml注意事项--controller接受参数以及参数校验--异常统一管理以及aop的使用---整合mybatis---swagger2构建api文档---jpa访问数据库及page进行分页---整合redis---定时任务

    springboot学习-jdbc操作数据库--yml注意事项--controller接受参数以及参数校验-- 异常统一管理以及aop的使用---整合mybatis---swagger2构建api文档 ...

  7. springboot项目--传入参数校验-----SpringBoot开发详解(五)--Controller接收参数以及参数校验----https://blog.csdn.net/qq_31001665/article/details/71075743

    https://blog.csdn.net/qq_31001665/article/details/71075743 springboot项目--传入参数校验-----SpringBoot开发详解(五 ...

  8. springboot 接口参数校验

    前言 在开发接口的时候,参数校验是必不可少的.参数的类型,长度等规则,在开发初期都应该由产品经理或者技术负责人等来约定.如果不对入参做校验,很有可能会因为一些不合法的参数而导致系统出现异常. 上一篇文 ...

  9. Java web服务端参数校验Javax.validation (springboot)

    一.基本使用 Javax.validation是spring集成自带的一个参数校验接口.可通过添加注解来设置校验条件. 下面以springboot项目为例进行说明.创建web项目后,不需要再添加其他的 ...

随机推荐

  1. Linux内核调试方法总结之Jprobes

    Jprobes [用途] 类似于Kprobes和Return Probes,区别在于,Kprobes可以在任意指令处插入探针,Jprobes只在函数入口插入探针,而Return Probes则是在函数 ...

  2. EF6中一个关于时间类型 datetime2 的坑

    在一个访问下位机的程序中,返回的时间戳有时候因断线产生0001年01月01日的时间,而原先使用拼接SQL进行数据存储的操作时,这个问题是可以跳过的. 这次把拼接SQL的部分重新改为EF进行管理,这个坑 ...

  3. spring监听机制——观察者模式的应用

    使用方法 spring监听模式需要三个组件: 1. 事件,需要继承ApplicationEvent,即观察者模式中的"主题",可以看做一个普通的bean类,用于保存在事件监听器的业 ...

  4. 如何减小VMware虚拟机硬盘空间

    VMware是微软出品的目前最好的虚拟机件,利用虚拟机可轻松实现多系统同时运行.特别需要多个系统来完成不同功能的者更是需要,VMware是最好的选择,在这里介绍一些VMware虚拟机使用的小技巧,本文 ...

  5. 测开之路一百:jquery引用、语法、事件

    工作中一般会使用jquery代替js,jquery官网:https://jquery.com/ 引用jquery: 第一种方式:下载引用: jquery下载官网:https://jquery.com/ ...

  6. DlgResToDlgTemplate 的代码,提取EXE中的资源,然后转化成C的字符串数组

    代码来源:https://www.codeproject.com/Articles/13330/Using-Dialog-Templates-to-create-an-InputBox-in-C #i ...

  7. C#怎么让字符串定长,不够的用空格补齐

    string.PadLeft 或者 string.PadRight  : string.PadLeft 表示如果一个字符串的长度小于指定的值,则在字符串的左侧(也就是前面)用指定的字符填充,直到字符串 ...

  8. IDEA基本设置和快捷键大全

    # IDEA基本设置 ## 设置编码格式 1. Configure - Settings - Editor - File Encodings 2. 将三个编码全部设置为UTF-8 ## 启用Ctrl+ ...

  9. 【ABAP系列】SAP ABAP POPUP弹出框自建内容

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[MM系列]SAP ABAP POPUP弹出框自 ...

  10. Vue的生命周期(在其他地方看到一份非常好又详细的详解)

    链接地址:https://segmentfault.com/a/1190000011381906 首先,每个Vue实例在被创建之前都要经过一系列的初始化过程,这个过程就是vue的生命周期.首先看一张图 ...