欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

spring boot輸入數(shù)據(jù)校驗(yàn)(validation)的實(shí)現(xiàn)過(guò)程

 更新時(shí)間:2021年09月22日 09:11:39   作者:吳吃辣  
web項(xiàng)目中,用戶的輸入總是被假定不安全不正確的,在被處理前需要做校驗(yàn)。本文介紹在spring boot項(xiàng)目中實(shí)現(xiàn)數(shù)據(jù)校驗(yàn)的過(guò)程,通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧

項(xiàng)目?jī)?nèi)容

實(shí)現(xiàn)一個(gè)簡(jiǎn)單的用戶注冊(cè)接口,演示怎樣進(jìn)行數(shù)據(jù)校驗(yàn)。

要求

  • JDK1.8或更新版本
  • Eclipse開(kāi)發(fā)環(huán)境

如沒(méi)有開(kāi)發(fā)環(huán)境,可參考 [spring boot 開(kāi)發(fā)環(huán)境搭建(Eclipse)]。

項(xiàng)目創(chuàng)建

創(chuàng)建spring boot項(xiàng)目

打開(kāi)Eclipse,創(chuàng)建spring boot的spring starter project項(xiàng)目,選擇菜單:File > New > Project ...,彈出對(duì)話框,選擇:Spring Boot > Spring Starter Project,在配置依賴時(shí),勾選web,完成項(xiàng)目創(chuàng)建。

項(xià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>

代碼實(shí)現(xiàn)

項(xiàng)目目錄結(jié)構(gòu)如下圖,添加了幾個(gè)類,下面將詳細(xì)介紹。

創(chuàng)建RegisterRequest

用戶注冊(cè)時(shí),要求輸入手機(jī)號(hào)、密碼、昵稱,創(chuàng)建RegisterRequest類來(lái)接受前端傳過(guò)來(lái)的數(shù)據(jù),同時(shí)校驗(yàn)數(shù)據(jù),校驗(yàn)都是通過(guò)注解的方式實(shí)現(xiàn)。

public class RegisterRequest {
	
	@SuppressWarnings("unused")
	private static final org.slf4j.Logger log = LoggerFactory.getLogger(RegisterRequest.class);
	
	@NotNull(message="手機(jī)號(hào)必須填")
	@Pattern(regexp = "^[1]([3][0-9]{1}|59|58|88|89)[0-9]{8}$", message="賬號(hào)請(qǐng)輸入11位手機(jī)號(hào)") // 手機(jī)號(hào)
	private String mobile;
	
	@NotNull(message="昵稱必須填")
	@Size(min=1, max=20, message="昵稱1~20個(gè)字")
	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;
	}
    	
}

說(shuō)明

RegisterRequest類有3個(gè)成員變量:mobile,nickname, password,這些變量都帶有注解:

  • @NotNull 表示必填
  • @Size 字符串長(zhǎng)度必須符合指定范圍
  • @Pattern 輸入字符串必須匹配正則表達(dá)式

創(chuàng)建控制器

我們創(chuàng)建AuthController控制器類,實(shí)現(xiàn)一個(gè)用戶注冊(cè)的接口:

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("輸入錯(cuò)誤");
//			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);
    }
}

說(shuō)明

方法register有2個(gè)參數(shù)

  • @Valid @RequestBody RegisterRequest register@RequestBody 表明輸入來(lái)自請(qǐng)求body,@Valid表明在綁定輸入時(shí)作校驗(yàn)
  • BindingResult bindingResult 這個(gè)參數(shù)存放校驗(yàn)結(jié)果

輔助類 MiscUtil,Result

直接返回bindingResult過(guò)于復(fù)雜,使用MiscUtil.getValidateError簡(jiǎn)化校驗(yàn)結(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, "輸入錯(cuò)誤"); //rfc4918 - 11.2. 422: Unprocessable Entity
		ret.putData("fieldErrors", fieldErrors);
		
		return ret;
	}

Result是結(jié)果封裝類,[spring boot 接口返回值封裝] 那一篇中已經(jīng)介紹過(guò)。

運(yùn)行

Eclipse左側(cè),在項(xiàng)目根目錄上點(diǎn)擊鼠標(biāo)右鍵彈出菜單,選擇:run as -> spring boot app 運(yùn)行程序。 打開(kāi)Postman訪問(wèn)接口,運(yùn)行結(jié)果如下:

輸入錯(cuò)誤的情況

輸入正確的情況

總結(jié)

完整代碼

到此這篇關(guān)于spring boot輸入數(shù)據(jù)校驗(yàn)(validation)的文章就介紹到這了,更多相關(guān)spring boot數(shù)據(jù)校驗(yàn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot整合WebService的實(shí)現(xiàn)示例

    SpringBoot整合WebService的實(shí)現(xiàn)示例

    本文主要介紹了SpringBoot整合WebService,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • SpringBoot集成PostgreSQL并設(shè)置最大連接數(shù)

    SpringBoot集成PostgreSQL并設(shè)置最大連接數(shù)

    本文主要介紹了SpringBoot集成PostgreSQL并設(shè)置最大連接數(shù),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-11-11
  • DecimalFormat數(shù)字格式化用法詳解

    DecimalFormat數(shù)字格式化用法詳解

    這篇文章主要為大家詳細(xì)介紹了DecimalFormat數(shù)字格式化用法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-03-03
  • Java設(shè)計(jì)模式編程中簡(jiǎn)單工廠與抽象工廠模式的使用實(shí)例

    Java設(shè)計(jì)模式編程中簡(jiǎn)單工廠與抽象工廠模式的使用實(shí)例

    這篇文章主要介紹了Java設(shè)計(jì)模式編程中簡(jiǎn)單工廠與抽象工廠模式的使用實(shí)例,簡(jiǎn)單工廠與抽象工廠都可以歸類于設(shè)計(jì)模式中的創(chuàng)建型模式,需要的朋友可以參考下
    2016-04-04
  • java應(yīng)用程序如何自定義log4j配置文件的位置

    java應(yīng)用程序如何自定義log4j配置文件的位置

    這篇文章主要介紹了java應(yīng)用程序如何自定義log4j配置文件的位置,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Java中的構(gòu)造方法this、super的用法詳解

    Java中的構(gòu)造方法this、super的用法詳解

    這篇文章較詳細(xì)的給大家介紹了Java中的構(gòu)造方法this、super的用法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2018-07-07
  • Springboot加載所有Bean之后運(yùn)行方式

    Springboot加載所有Bean之后運(yùn)行方式

    這篇文章主要介紹了Springboot加載所有Bean之后運(yùn)行方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-07-07
  • 關(guān)于SpringBoot中的XA事務(wù)詳解

    關(guān)于SpringBoot中的XA事務(wù)詳解

    這篇文章主要介紹了關(guān)于SpringBoot中的XA事務(wù)詳解,事務(wù)管理可以確保數(shù)據(jù)的一致性和完整性,同時(shí)也可以避免數(shù)據(jù)丟失和沖突等問(wèn)題。在分布式環(huán)境中,XA?事務(wù)是一種常用的事務(wù)管理方式,需要的朋友可以參考下
    2023-07-07
  • java垃圾回收之實(shí)現(xiàn)并行GC算法

    java垃圾回收之實(shí)現(xiàn)并行GC算法

    這篇文章主要為大家介紹了java垃圾回收之實(shí)現(xiàn)并行GC算法的詳細(xì)講解,讓我們看看并行垃圾收集器的GC日志長(zhǎng)什么樣,?從中我們可以得到哪些有用信息
    2022-01-01
  • java中生成任意之間數(shù)的隨機(jī)數(shù)詳解

    java中生成任意之間數(shù)的隨機(jī)數(shù)詳解

    這篇文章主要介紹了java中生成任意之間數(shù)的隨機(jī)數(shù)詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09

最新評(píng)論