本文仅实现了api接口基本的参数校验,还有更多的校验场景,可以参考文章底部的参考链接

使用starter 创建 SpringBoot项目,并添加依赖

依赖

1、单独使用

org.hibernate

hibernate-validator

6.0.1.Final

2、在Spring Boot中使用

注意: Spring Boot 2.3以前的版本是默认引入了spring-boot-starter-validation的,不需要额外引入 springboot-2.3开始,校验包被独立成了一个 starter组件

org.springframework.boot

spring-boot-starter-validation

完整依赖

1.8

UTF-8

UTF-8

2.3.7.RELEASE

org.springframework.boot

spring-boot-starter

org.springframework.boot

spring-boot-starter-web

org.projectlombok

lombok

true

org.hibernate

hibernate-validator

6.0.1.Final

文件入口

package com.example.demo;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class DemoApplication {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

}

}

定义校验规则

package com.example.demo.dto;

import lombok.Data;

import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotNull;

@Data

public class UserDTO {

private Long userId;

@NotNull

@Length(min = 2, max = 10)

private String userName;

@NotNull

@Length(min = 6, max = 20)

private String account;

@NotNull

@Length(min = 6, max = 20)

private String password;

}

统一的数据返回

package com.example.demo.common;

/**

* 统一的数据返回

*/

public class JsonResult {

private Integer code;

private String msg;

private Object data;

public JsonResult(Integer code, String msg, Object data) {

this.code = code;

this.msg = msg;

this.data = data;

}

public static JsonResult success(Object data){

return new JsonResult(0, "success", data);

}

public static JsonResult error(String errorMessage) {

return new JsonResult(-1, errorMessage, null);

}

public Integer getCode() {

return code;

}

public void setCode(Integer code) {

this.code = code;

}

public String getMsg() {

return msg;

}

public void setMsg(String msg) {

this.msg = msg;

}

public Object getData() {

return data;

}

public void setData(Object data) {

this.data = data;

}

}

全局异常处理

package com.example.demo.common;

import org.springframework.http.HttpStatus;

import org.springframework.validation.BindingResult;

import org.springframework.validation.FieldError;

import org.springframework.web.bind.MethodArgumentNotValidException;

import org.springframework.web.bind.annotation.ExceptionHandler;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.bind.annotation.ResponseStatus;

import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**

* 全局异常处理

*/

@RestControllerAdvice

public class CommonExceptionHandler {

/**

* 参数校验失败

*

* @param ex

* @return

*/

@ExceptionHandler({MethodArgumentNotValidException.class})

@ResponseStatus(HttpStatus.OK)

@ResponseBody

public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {

BindingResult bindingResult = ex.getBindingResult();

StringBuilder sb = new StringBuilder("校验失败:");

for (FieldError fieldError : bindingResult.getFieldErrors()) {

sb.append(fieldError.getField())

.append(":")

.append(fieldError.getDefaultMessage())

.append(", ");

}

String msg = sb.toString();

return JsonResult.error("参数校验失败" + msg);

}

/**

* 参数校验失败

*

* @param ex

* @return

*/

@ExceptionHandler({ConstraintViolationException.class})

@ResponseStatus(HttpStatus.OK)

@ResponseBody

public JsonResult handleConstraintViolationException(ConstraintViolationException ex) {

return JsonResult.error("参数校验失败" + ex.getMessage());

}

}

控制器

package com.example.demo.controller;

import org.springframework.validation.annotation.Validated;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RestController;

import com.example.demo.common.JsonResult;

import com.example.demo.dto.UserDTO;

@RestController

public class UserController {

@PostMapping("/save")

public JsonResult saveUser(@RequestBody @Validated UserDTO userDTO) {

// 校验通过,才会执行业务逻辑处理

System.out.println(userDTO);

return JsonResult.success(userDTO);

}

}

HTTP Client配置

http-client.env.json

{

"dev": {

"baseUrl": "http://localhost:8080"

}

}

接口测试文件

user.http

POST {{baseUrl}}/save

content-type: application/json

{

"name": "Tom"

}

###

POST {{baseUrl}}/save

content-type: application/json

{

"userName": "Tom"

}

###

POST {{baseUrl}}/save

content-type: application/json

{

"userName": "Tom",

"password": "11"

}

###

POST {{baseUrl}}/save

content-type: application/json

{

"userName": "Tom",

"password": "1133344"

}

###

POST {{baseUrl}}/save

content-type: application/json

{

"userName": "Tom",

"password": "1133344",

"account": "account"

}

###

注解功能@AssertFalse可以为null,如果不为null的话必须为false@AssertTrue可以为null,如果不为null的话必须为true@DecimalMax设置不能超过最大值@DecimalMin设置不能超过最小值@Digits设置必须是数字且数字整数的位数和小数的位数必须在指定范围内@Future日期必须在当前日期的未来@Past日期必须在当前日期的过去@Max最大不得超过此最大值@Min最大不得小于此最小值@NotNull不能为null,可以是空@Null必须为null@Pattern必须满足指定的正则表达式@Size集合、数组、map等的size()值必须在指定范围内@Email必须是email格式@Length长度必须在指定范围内@NotBlank字符串不能为null,字符串trim()后也不能等于“”@NotEmpty不能为null,集合、数组、map等size()不能为0;字符串trim()后可以等于“”@Range值必须在指定范围内@URL必须是一个URL

参考 SpringBoot 实现各种参数校验 SpingBoot项目使用@Validated和@Valid参数校验 SpringBoot 如何进行参数校验,老鸟们都这么玩的!

好文链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: