spring boot輸入數(shù)據(jù)校驗(validation)的實現(xiàn)過程
項目內(nèi)容
實現(xiàn)一個簡單的用戶注冊接口,演示怎樣進(jìn)行數(shù)據(jù)校驗。
要求
- JDK1.8或更新版本
- Eclipse開發(fā)環(huán)境
如沒有開發(fā)環(huán)境,可參考 [spring boot 開發(fā)環(huán)境搭建(Eclipse)]。
項目創(chuàng)建
創(chuàng)建spring boot項目
打開Eclipse,創(chuàng)建spring boot的spring starter project項目,選擇菜單:File > New > Project ...,彈出對話框,選擇:Spring Boot > Spring Starter Project,在配置依賴時,勾選web,完成項目創(chuàng)建。

項目依賴
pom.xml的內(nèi)容
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.qikegu</groupId> <artifactId>springboot-validation-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot-validation-demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
代碼實現(xiàn)
項目目錄結(jié)構(gòu)如下圖,添加了幾個類,下面將詳細(xì)介紹。

創(chuàng)建RegisterRequest類
用戶注冊時,要求輸入手機號、密碼、昵稱,創(chuàng)建RegisterRequest類來接受前端傳過來的數(shù)據(jù),同時校驗數(shù)據(jù),校驗都是通過注解的方式實現(xiàn)。
public class RegisterRequest {
@SuppressWarnings("unused")
private static final org.slf4j.Logger log = LoggerFactory.getLogger(RegisterRequest.class);
@NotNull(message="手機號必須填")
@Pattern(regexp = "^[1]([3][0-9]{1}|59|58|88|89)[0-9]{8}$", message="賬號請輸入11位手機號") // 手機號
private String mobile;
@NotNull(message="昵稱必須填")
@Size(min=1, max=20, message="昵稱1~20個字")
private String nickname;
@NotNull(message="密碼必須填")
@Size(min=6, max=16, message="密碼6~16位")
private String password;
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
說明
RegisterRequest類有3個成員變量:mobile,nickname, password,這些變量都帶有注解:
- @NotNull 表示必填
- @Size 字符串長度必須符合指定范圍
- @Pattern 輸入字符串必須匹配正則表達(dá)式
創(chuàng)建控制器
我們創(chuàng)建AuthController控制器類,實現(xiàn)一個用戶注冊的接口:
package com.qikegu.demo.controller;
import javax.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.qikegu.demo.common.util.MiscUtil;
import com.qikegu.demo.common.util.Result;
import com.qikegu.demo.model.RegisterRequest;
@RestController
@RequestMapping("/auth")
public class AuthController {
@RequestMapping(value = "/register", method = RequestMethod.POST, produces="application/json")
public ResponseEntity<Result> register(
@Valid @RequestBody RegisterRequest register,
BindingResult bindingResult
) {
if(bindingResult.hasErrors()) {
//rfc4918 - 11.2. 422: Unprocessable Entity
// res.setStatus(422);
// res.setMessage("輸入錯誤");
// res.putData("fieldErrors", bindingResult.getFieldErrors());
Result res1 = MiscUtil.getValidateError(bindingResult);
return new ResponseEntity<Result>(res1, HttpStatus.UNPROCESSABLE_ENTITY);
}
Result res = new Result(200, "ok");
return ResponseEntity.ok(res);
}
}
說明
方法register有2個參數(shù)
@Valid @RequestBody RegisterRequest register@RequestBody 表明輸入來自請求body,@Valid表明在綁定輸入時作校驗BindingResult bindingResult這個參數(shù)存放校驗結(jié)果
輔助類 MiscUtil,Result
直接返回bindingResult過于復(fù)雜,使用MiscUtil.getValidateError簡化校驗結(jié)果
static public Result getValidateError(BindingResult bindingResult) {
if(bindingResult.hasErrors() == false)
return null;
Map<String,String> fieldErrors = new HashMap<String, String>();
for(FieldError error : bindingResult.getFieldErrors()){
fieldErrors.put(error.getField(), error.getCode() + "|" + error.getDefaultMessage());
}
Result ret = new Result(422, "輸入錯誤"); //rfc4918 - 11.2. 422: Unprocessable Entity
ret.putData("fieldErrors", fieldErrors);
return ret;
}
Result是結(jié)果封裝類,[spring boot 接口返回值封裝] 那一篇中已經(jīng)介紹過。
運行
Eclipse左側(cè),在項目根目錄上點擊鼠標(biāo)右鍵彈出菜單,選擇:run as -> spring boot app 運行程序。 打開Postman訪問接口,運行結(jié)果如下:
輸入錯誤的情況

輸入正確的情況

總結(jié)
到此這篇關(guān)于spring boot輸入數(shù)據(jù)校驗(validation)的文章就介紹到這了,更多相關(guān)spring boot數(shù)據(jù)校驗內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot + validation 接口參數(shù)校驗的思路詳解
- Spring?Boot集成validation實現(xiàn)參數(shù)校驗功能
- SpringBoot使用Validation包進(jìn)行輸入?yún)?shù)校驗
- spring?boot?validation參數(shù)校驗與分組嵌套各種類型及使用小結(jié)
- springboot中使用Hibernate-Validation校驗參數(shù)詳解
- SpringBoot使用Validation進(jìn)行參數(shù)校驗的示例詳解
- spring-boot-starter-validation?校驗參數(shù)的實現(xiàn)
- 從零到掌握Spring Boot Validation 接口校驗的詳細(xì)過程
相關(guān)文章
淺析Android系統(tǒng)中HTTPS通信的實現(xiàn)
這篇文章主要介紹了淺析Android系統(tǒng)中HTTPS通信的實現(xiàn),實現(xiàn)握手的源碼為Java語言編寫,需要的朋友可以參考下2015-07-07
springboot?通過博途獲取plc點位的數(shù)據(jù)代碼實現(xiàn)
這篇文章主要介紹了springboot?通過博途獲取plc點位的數(shù)據(jù)的代碼實現(xiàn),本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08
Spring-AOP-ProceedingJoinPoint的使用詳解
這篇文章主要介紹了Spring-AOP-ProceedingJoinPoint的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-03-03

