目錄
什么是不优雅的参数校验
实现案例
POM
请求参数封装
Controller中获取参数绑定结果
校验结果
进一步理解
Validation分组校验?
@Validate和@Valid什么区别?
有哪些常用的校验?
自定义validation?
首頁 Java java教程 SpringBoot介面怎麼對參數進行校驗

SpringBoot介面怎麼對參數進行校驗

May 22, 2023 pm 08:49 PM
springboot

什么是不优雅的参数校验

后端对前端传过来的参数也是需要进行校验的,如果在controller中直接校验需要用大量的if else做判断

以添加用户的接口为例,需要对前端传过来的参数进行校验, 如下的校验就是不优雅的:

@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("add")
public ResponseEntity<String> add(User user){
if(user.getName()==null) {
return ResponseResult.fail("user name should not be empty");
} else if(user.getName().length()<5 || user.getName().length()>50){
return ResponseResult.fail("user name length should between 5-50");
}
if(user.getAge()< 1 || user.getAge()> 150) {
return ResponseResult.fail("invalid age");
}
// ...
return ResponseEntity.ok("success");
}
}
登入後複製

针对这个普遍的问题,Java开者在Java API规范 (JSR303) 定义了Bean校验的标准validation-api,但没有提供实现。

hibernate validation是对这个规范的实现,并增加了校验注解如@Email、@Length等。

Spring Validation是对hibernate validation的二次封装,用于支持spring mvc参数自动校验。

接下来,我们以springboot项目为例,介绍Spring Validation的使用。

实现案例

本案例使用了 Spring Validation 对参数绑定进行了验证,主要为您提供参数验证的思路。请参考SpringBoot如何封装接口统一错误信息处理,其中包括针对绑定参数检查错误的处理

POM

添加pom依赖:

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
登入後複製

请求参数封装

单一职责,所以将查询用户的参数封装到UserParam中, 而不是User(数据库实体)本身。

对每个参数字段添加validation注解约束和message。

/**
* user.
*
* @author pdai
*/
@Data
@Builder
@ApiModel(value = "User", subTypes = {AddressParam.class})
public class UserParam implements Serializable {
private static final long serialVersionUID = 1L;
@NotEmpty(message = "could not be empty")
private String userId;
@NotEmpty(message = "could not be empty")
@Email(message = "invalid email")
private String email;
@NotEmpty(message = "could not be empty")
@Pattern(regexp = "^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$", message = "invalid ID")
private String cardNo;
@NotEmpty(message = "could not be empty")
@Length(min = 1, max = 10, message = "nick name should be 1-10")
private String nickName;
@NotEmpty(message = "could not be empty")
@Range(min = 0, max = 1, message = "sex should be 0-1")
private int sex;
@Max(value = 100, message = "Please input valid age")
private int age;
@Valid
private AddressParam address;
}
登入後複製

Controller中获取参数绑定结果

使用@Valid或者@Validate注解,参数校验的值放在BindingResult中

/**
* @author pdai
*/
@Slf4j
@Api(value = "User Interfaces", tags = "User Interfaces")
@RestController
@RequestMapping("/user")
public class UserController {

/**
* http://localhost:8080/user/add .
*
* @param userParam user param
* @return user
*/
@ApiOperation("Add User")
@ApiImplicitParam(name = "userParam", type = "body", dataTypeClass = UserParam.class, required = true)
@PostMapping("add")
public ResponseEntity<String> add(@Valid @RequestBody UserParam userParam, BindingResult bindingResult){
if (bindingResult.hasErrors()) {
List<ObjectError> errors = bindingResult.getAllErrors();
errors.forEach(p -> {
FieldError fieldError = (FieldError) p;
log.error("Invalid Parameter : object - {},field - {},errorMessage - {}", fieldError.getObjectName(), fieldError.getField(), fieldError.getDefaultMessage());
});
return ResponseEntity.badRequest().body("invalid parameter");
}
return ResponseEntity.ok("success");
}
}
登入後複製

校验结果

POST访问添加User的请求

SpringBoot介面怎麼對參數進行校驗

后台输出参数绑定错误信息:(包含哪个对象,哪个字段,什么样的错误描述)

2021-09-16 10:37:05.173 ERROR 21216 --- [nio-8080-exec-8] t.p.s.v.controller.UserController : Invalid Parameter : object - userParam,field - nickName,errorMessage - could not be empty
2021-09-16 10:37:05.176 ERROR 21216 --- [nio-8080-exec-8] t.p.s.v.controller.UserController : Invalid Parameter : object - userParam,field - email,errorMessage - could not be empty
2021-09-16 10:37:05.176 ERROR 21216 --- [nio-8080-exec-8] t.p.s.v.controller.UserController : Invalid Parameter : object - userParam,field - cardNo,errorMessage - could not be empty

(本例只是springboot-validation的简单用例,针对接口统一的错误信息封装请看SpringBoot接口如何统一异常处理

进一步理解

我们再通过一些问题来帮助你更深入理解validation校验。@pdai

Validation分组校验?

上面的例子中,其实存在一个问题,UserParam既可以作为addUser的参数(id为空),又可以作为updateUser的参数(id不能为空),这时候怎么办呢?分组校验登场。

@Data
@Builder
@ApiModel(value = "User", subTypes = {AddressParam.class})
public class UserParam implements Serializable {
private static final long serialVersionUID = 1L;
@NotEmpty(message = "could not be empty") // 这里定为空,对于addUser时是不合适的
private String userId;
}
登入後複製

这时候可以使用Validation分组

  • 先定义分组(无需实现接口)

public interface AddValidationGroup {
}
public interface EditValidationGroup {
}
登入後複製
  • 在UserParam的userId字段添加分组

@Data
@Builder
@ApiModel(value = "User", subTypes = {AddressParam.class})
public class UserParam implements Serializable {
private static final long serialVersionUID = 1L;
@NotEmpty(message = "{user.msg.userId.notEmpty}", groups = {EditValidationGroup.class}) // 这里
private String userId;
}
登入後複製
  • controller中的接口使用校验时使用分组

PS: 需要使用@Validated注解

@Slf4j
@Api(value = "User Interfaces", tags = "User Interfaces")
@RestController
@RequestMapping("/user")
public class UserController {

/**
* http://localhost:8080/user/add .
*
* @param userParam user param
* @return user
*/
@ApiOperation("Add User")
@ApiImplicitParam(name = "userParam", type = "body", dataTypeClass = UserParam.class, required = true)
@PostMapping("add")
public ResponseEntity<UserParam> add(@Validated(AddValidationGroup.class){
return ResponseEntity.ok(userParam);
}
/**
* http://localhost:8080/user/add .
*
* @param userParam user param
* @return user
*/
@ApiOperation("Edit User")
@ApiImplicitParam(name = "userParam", type = "body", dataTypeClass = UserParam.class, required = true)
@PostMapping("edit")
public ResponseEntity<UserParam> edit(@Validated(EditValidationGroup.class){
return ResponseEntity.ok(userParam);
}
}
登入後複製
  • 测试

SpringBoot介面怎麼對參數進行校驗

@Validate和@Valid什么区别?

你会注意到,在前面的例子中使用的是@Validate而不是@Valid,你可能会想知道它们之间的不同之处

在检验Controller的入参是否符合规范时,使用@Validated或者@Valid在基本验证功能上没有太多区别。但是在分组、注解地方、嵌套验证等功能上两个有所不同:

  • 分组

@Validated:提供了一个分组功能,可以在入参验证时,根据不同的分组采用不同的验证机制,这个网上也有资料,不详述。JSR-303标准并未包含分组功能。

  • 注解地方

@Validated:可以用在类型、方法和方法参数上。但是不能用在成员属性(字段)上

@Valid:可以用在方法、构造函数、方法参数和成员属性(字段)上

  • 嵌套类型

比如本文例子中的address是user的一个嵌套属性, 只能用@Valid

@Data
@Builder
@ApiModel(value = "User", subTypes = {AddressParam.class})
public class UserParam implements Serializable {
private static final long serialVersionUID = 1L;
@Valid // 这里只能用@Valid
private AddressParam address;
}
登入後複製

有哪些常用的校验?

从以下三类理解。

  • JSR303/JSR-349: JSR303是一项标准,只提供规范不提供实现,规定一些校验规范即校验注解,如@Null,@NotNull,@Pattern,位于javax.validation.constraints包下。JSR-349是其的升级版本,添加了一些新特性

@AssertFalse 被注释的元素只能为false
@AssertTrue 被注释的元素只能为true
@DecimalMax 被注释的元素必须小于或等于{value}
@DecimalMin 被注释的元素必须大于或等于{value}
@Digits 被注释的元素数字的值超出了允许范围(只允许在{integer}位整数和{fraction}位小数范围内)
@Email 被注释的元素不是一个合法的电子邮件地址
@Future 被注释的元素需要是一个将来的时间
@FutureOrPresent 被注释的元素需要是一个将来或现在的时间
@Max 被注释的元素最大不能超过{value}
@Min 被注释的元素最小不能小于{value}
@Negative 被注释的元素必须是负数
@NegativeOrZero 被注释的元素必须是负数或零
@NotBlank 被注释的元素不能为空
@NotEmpty 被注释的元素不能为空
@NotNull 被注释的元素不能为null
@Null 被注释的元素必须为null
@Past 被注释的元素需要是一个过去的时间
@PastOrPresent 被注释的元素需要是一个过去或现在的时间
@Pattern 被注释的元素需要匹配正则表达式"{regexp}"
@Positive 被注释的元素必须是正数
@PositiveOrZero 被注释的元素必须是正数或零
@Size 被注释的元素个数必须在{min}和{max}之间
登入後複製
  • hibernate validation:hibernate validation是对这个规范的实现,并增加了一些其他校验注解,如@Email,@Length,@Range等等

@CreditCardNumber 被注释的元素不合法的信用卡号码
@Currency 被注释的元素不合法的货币 (必须是{value}其中之一)
@EAN 被注释的元素不合法的{type}条形码
@Email 被注释的元素不是一个合法的电子邮件地址 (已过期)
@Length 被注释的元素长度需要在{min}和{max}之间
@CodePointLength 被注释的元素长度需要在{min}和{max}之间
@LuhnCheck 被注释的元素${validatedValue}的校验码不合法, Luhn模10校验和不匹配
@Mod10Check 被注释的元素${validatedValue}的校验码不合法, 模10校验和不匹配
@Mod11Check 被注释的元素${validatedValue}的校验码不合法, 模11校验和不匹配
@ModCheck 被注释的元素${validatedValue}的校验码不合法, ${modType}校验和不匹配 (已过期)
@NotBlank 被注释的元素不能为空 (已过期)
@NotEmpty 被注释的元素不能为空 (已过期)
@ParametersScriptAssert 被注释的元素执行脚本表达式"{script}"没有返回期望结果
@Range 被注释的元素需要在{min}和{max}之间
@SafeHtml 被注释的元素可能有不安全的HTML内容
@ScriptAssert 被注释的元素执行脚本表达式"{script}"没有返回期望结果
@URL 被注释的元素需要是一个合法的URL
@DurationMax 被注释的元素必须小于${inclusive == true ? &#39;或等于&#39; : &#39;&#39;}${days == 0 ? &#39;&#39; : days += &#39;天&#39;}${hours == 0 ? &#39;&#39; : hours += &#39;小时&#39;}${minutes == 0 ? &#39;&#39; : minutes += &#39;分钟&#39;}${seconds == 0 ? &#39;&#39; : seconds += &#39;秒&#39;}${millis == 0 ? &#39;&#39; : millis += &#39;毫秒&#39;}${nanos == 0 ? &#39;&#39; : nanos += &#39;纳秒&#39;}
@DurationMin 被注释的元素必须大于${inclusive == true ? &#39;或等于&#39; : &#39;&#39;}${days == 0 ? &#39;&#39; : days += &#39;天&#39;}${hours == 0 ? &#39;&#39; : hours += &#39;小时&#39;}${minutes == 0 ? &#39;&#39; : minutes += &#39;分钟&#39;}${seconds == 0 ? &#39;&#39; : seconds += &#39;秒&#39;}${millis == 0 ? &#39;&#39; : millis += &#39;毫秒&#39;}${nanos == 0 ? &#39;&#39; : nanos += &#39;纳秒&#39;}
登入後複製
  • spring validation:spring validation对hibernate validation进行了二次封装,在springmvc模块中添加了自动校验,并将校验信息封装进了特定的类中

自定义validation?

如果上面的注解不能满足我们检验参数的要求,我们能不能自定义校验规则呢? 可以。

  • 定义注解

package tech.pdai.springboot.validation.group.validation.custom;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {TelephoneNumberValidator.class}) // 指定校验器
public @interface TelephoneNumber {
String message() default "Invalid telephone number";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
登入後複製
  • 定义校验器

public class TelephoneNumberValidator implements ConstraintValidator<TelephoneNumber, String> {
private static final String REGEX_TEL = "0\\d{2,3}[-]?\\d{7,8}|0\\d{2,3}\\s?\\d{7,8}|13[0-9]\\d{8}|15[1089]\\d{8}";
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext){
try {
return Pattern.matches(REGEX_TEL, s);
} catch (Exception e) {
return false;
}
}
}
登入後複製

使用

@Data
@Builder
@ApiModel(value = "User", subTypes = {AddressParam.class})
public class UserParam implements Serializable {
private static final long serialVersionUID = 1L;
@NotEmpty(message = "{user.msg.userId.notEmpty}", groups = {EditValidationGroup.class})
private String userId;
@TelephoneNumber(message = "invalid telephone number") // 这里
private String telephone;
}
登入後複製

以上是SpringBoot介面怎麼對參數進行校驗的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Springboot怎麼整合Jasypt實現設定檔加密 Springboot怎麼整合Jasypt實現設定檔加密 Jun 01, 2023 am 08:55 AM

Jasypt介紹Jasypt是一個java庫,它允許開發員以最少的努力為他/她的專案添加基本的加密功能,並且不需要對加密工作原理有深入的了解用於單向和雙向加密的高安全性、基於標準的加密技術。加密密碼,文本,數字,二進位檔案...適合整合到基於Spring的應用程式中,開放API,用於任何JCE提供者...添加如下依賴:com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt好處保護我們的系統安全,即使程式碼洩露,也可以保證資料來源的

SpringBoot怎麼整合Redisson實現延遲隊列 SpringBoot怎麼整合Redisson實現延遲隊列 May 30, 2023 pm 02:40 PM

使用場景1、下單成功,30分鐘未支付。支付超時,自動取消訂單2、訂單簽收,簽收後7天未進行評估。訂單超時未評價,系統預設好評3、下單成功,商家5分鐘未接單,訂單取消4、配送超時,推播簡訊提醒…對於延時比較長的場景、即時性不高的場景,我們可以採用任務調度的方式定時輪詢處理。如:xxl-job今天我們採

怎麼在SpringBoot中使用Redis實現分散式鎖 怎麼在SpringBoot中使用Redis實現分散式鎖 Jun 03, 2023 am 08:16 AM

一、Redis實現分散式鎖原理為什麼需要分散式鎖在聊分散式鎖之前,有必要先解釋一下,為什麼需要分散式鎖。與分散式鎖相對就的是單機鎖,我們在寫多執行緒程式時,避免同時操作一個共享變數產生資料問題,通常會使用一把鎖來互斥以保證共享變數的正確性,其使用範圍是在同一個進程中。如果換做是多個進程,需要同時操作一個共享資源,如何互斥?現在的業務應用通常是微服務架構,這也意味著一個應用會部署多個進程,多個進程如果需要修改MySQL中的同一行記錄,為了避免操作亂序導致髒數據,此時就需要引入分佈式鎖了。想要實現分

springboot讀取檔案打成jar包後存取不到怎麼解決 springboot讀取檔案打成jar包後存取不到怎麼解決 Jun 03, 2023 pm 04:38 PM

springboot讀取文件,打成jar包後訪問不到最新開發出現一種情況,springboot打成jar包後讀取不到文件,原因是打包之後,文件的虛擬路徑是無效的,只能通過流去讀取。文件在resources下publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

Springboot+Mybatis-plus不使用SQL語句進行多表新增怎麼實現 Springboot+Mybatis-plus不使用SQL語句進行多表新增怎麼實現 Jun 02, 2023 am 11:07 AM

在Springboot+Mybatis-plus不使用SQL語句進行多表添加操作我所遇到的問題準備工作在測試環境下模擬思維分解一下:創建出一個帶有參數的BrandDTO對像模擬對後台傳遞參數我所遇到的問題我們都知道,在我們使用Mybatis-plus中進行多表操作是極其困難的,如果你不使用Mybatis-plus-join這一類的工具,你只能去配置對應的Mapper.xml文件,配置又臭又長的ResultMap,然後再寫對應的sql語句,這種方法雖然看上去很麻煩,但具有很高的靈活性,可以讓我們

SpringBoot與SpringMVC的比較及差別分析 SpringBoot與SpringMVC的比較及差別分析 Dec 29, 2023 am 11:02 AM

SpringBoot和SpringMVC都是Java開發中常用的框架,但它們之間有一些明顯的差異。本文將探究這兩個框架的特點和用途,並對它們的差異進行比較。首先,我們來了解一下SpringBoot。 SpringBoot是由Pivotal團隊開發的,它旨在簡化基於Spring框架的應用程式的建立和部署。它提供了一種快速、輕量級的方式來建立獨立的、可執行

SpringBoot怎麼自訂Redis實作快取序列化 SpringBoot怎麼自訂Redis實作快取序列化 Jun 03, 2023 am 11:32 AM

1.自訂RedisTemplate1.1、RedisAPI預設序列化機制基於API的Redis快取實作是使用RedisTemplate範本進行資料快取操作的,這裡開啟RedisTemplate類,查看該類別的源碼資訊publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations,BeanClassLoaderAware{//聲明了value的各種序列化方式,初始值為空@NullableprivateRedisSe

springboot怎麼取得application.yml裡值 springboot怎麼取得application.yml裡值 Jun 03, 2023 pm 06:43 PM

在專案中,很多時候需要用到一些配置信息,這些信息在測試環境和生產環境下可能會有不同的配置,後面根據實際業務情況有可能還需要再做修改。我們不能將這些設定在程式碼中寫死,最好是寫到設定檔中,例如可以把這些資訊寫到application.yml檔案中。那麼,怎麼在程式碼裡取得或使用這個位址呢?有2個方法。方法一:我們可以透過@Value註解的${key}即可取得設定檔(application.yml)中和key對應的value值,這個方法適用於微服務比較少的情形方法二:在實際專案中,遇到業務繁瑣,邏

See all articles