SpringBoot使用validator校驗

在前臺表單驗證的時候,一般會校驗一些數據的可行性,好比是否爲空,長度,身份證,郵箱等等,那麼這樣是不是安全的呢,答案是否認的。由於也能夠經過模擬前臺請求等工具來直接提交到後臺,好比postman這樣的工具,那麼遇到這樣的問題怎麼辦呢,咱們能夠在後臺也作相應的校驗。前端

新建項目,由於本文會使用postman模擬前端請求,因此本文須要加入web依賴,pom文件以下:java

<?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>

	<groupId>com.dalaoyang</groupId>
	<artifactId>springboot_validator</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springboot_validator</name>
	<description>springboot_validator</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.9.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<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-devtools</artifactId>
			<scope>runtime</scope>
		</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>
複製代碼

建立一個demo類,說一下本文使用demo中校驗使用的註解:
@NotEmpty:非空
@Length:長度,最長或者最短
@Email:校驗email
@Pattern:使用正則校驗,本文使用的是身份證的正則
,代碼以下:git

package com.dalaoyang.entity;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

import javax.validation.constraints.Pattern;
import java.io.Serializable;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.entity
 * @email yangyang@dalaoyang.cn
 * @date 2018/5/1
 */
public class Demo implements Serializable {

    @NotEmpty(message="用戶名不能爲空")
    @Length(min=6,max = 12,message="用戶名長度必須位於6到12之間")
    private String userName;


    @NotEmpty(message="密碼不能爲空")
    @Length(min=6,message="密碼長度不能小於6位")
    private String passWord;

    @Email(message="請輸入正確的郵箱")
    private String email;

    @Pattern(regexp = "^(\\d{18,18}|\\d{15,15}|(\\d{17,17}[x|X]))$", message = "身份證格式錯誤")
    private String idCard;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getIdCard() {
        return idCard;
    }

    public void setIdCard(String idCard) {
        this.idCard = idCard;
    }

}
複製代碼

建立一個TestDemoController,來測試本文的校驗,代碼以下:web

package com.dalaoyang.controller;

import com.dalaoyang.entity.Demo;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.controller
 * @email yangyang@dalaoyang.cn
 * @date 2018/5/1
 */
@RestController
public class TestDemoController {

    @PostMapping("/")
    public String testDemo(@Valid Demo demo,BindingResult bindingResult){
        StringBuffer stringBuffer = new StringBuffer();
        if(bindingResult.hasErrors()){
            List<ObjectError> list =bindingResult.getAllErrors();
            for (ObjectError objectError:list) {
                stringBuffer.append(objectError.getDefaultMessage());
                stringBuffer.append("---");
            }
        }
        return stringBuffer!=null?stringBuffer.toString():"";
    }
}
複製代碼

啓動項目使用postman分別作了三次請求,第一次全部屬性都是隨便填寫的,如圖spring

第二次輸入正確的身份證和郵箱,用戶名和密碼爲空,如圖apache

第三次所有輸入正確,如圖安全

本文只是使用的簡單的幾種校驗,Hibernate-validator還有不少種校驗的方法,你們能夠參考這篇文章blog.csdn.net/xgblog/arti…springboot

源碼下載 :大老楊碼雲bash

我的網站:www.dalaoyang.cnapp

相關文章
相關標籤/搜索