一。pom.xml添加依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
二。實體類添加校驗規則:
package demo.rest;
import lombok.Data;
import lombok.ToString;
import javax.validation.constraints.NotNull;
/**
* description:
* author: yangzihe
* date: 2019-05-16 15:50
**/
@Data
@ToString
public class User {
@NotNull(message = "用戶名不可爲空")
private String name;
@NotNull(message = "密碼不可爲空")
private String password;
}
三。controller層添加驗證註解(使用BindingResult接收驗證結果):
package demo.rest;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* description:
* author: yangzihe
* date: 2019-05-16 15:48
**/
@RestController
public class DemoController {
@GetMapping("valid")
public String test1(@Validated User user, BindingResult result) {//@Valid註解也可
System.out.println(user);
System.out.println("result=" + result);
if (result.hasErrors()) {
StringBuilder sb = new StringBuilder();
for (ObjectError error : result.getAllErrors()) {
sb.append(error.getDefaultMessage() + ";");
}
System.out.println(sb.toString());
return sb.toString();
}
return "success";
}
}
四。啓動類啓動,瀏覽器訪問http://localhost:8080/valid:
@org.springframework.boot.autoconfigure.SpringBootApplication
public class SpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootApplication.class, args);
}
}
User(name=null, password=null)
result=org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'user' on field 'name': rejected value [null]; codes [NotNull.user.name,NotNull.name,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.name,name]; arguments []; default message [name]]; default message [用戶名不可爲空]
Field error in object 'user' on field 'password': rejected value [null]; codes [NotNull.user.password,NotNull.password,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.password,password]; arguments []; default message [password]]; default message [密碼不可爲空]
用戶名不可爲空;密碼不可爲空;
補充,常用驗證註解:
@Null 限制只能爲null
@NotNull 限制必須不爲null
@AssertFalse 限制必須爲false
@AssertTrue 限制必須爲true
@DecimalMax(value) 限制必須爲一個不大於指定值的數字
@DecimalMin(value) 限制必須爲一個不小於指定值的數字
@Digits(integer,fraction) 限制必須爲一個小數,且整數部分的位數不能超過integer,小數部分的位數不能超過fraction
@Future 限制必須是一個將來的日期
@Max(value) 限制必須爲一個不大於指定值的數字
@Min(value) 限制必須爲一個不小於指定值的數字
@Past 限制必須是一個過去的日期
@Pattern(value) 限制必須符合指定的正則表達式
@Size(max,min) 限制字符長度必須在min到max之間
@Past 驗證註解的元素值(日期類型)比當前時間早
@NotEmpty 驗證註解的元素值不爲null且不爲空(字符串長度不爲0、集合大小不爲0)
@NotBlank 驗證註解的元素值不爲空(不爲null、去除首位空格後長度爲0),不同於@NotEmpty,@NotBlank只應用於字符串且在比較時會去除字符串的空格
@Email 驗證註解的元素值是Email,也可以通過正則表達式和flag指定自定義的email格式
舉例:
@Pattern(regexp="^[a-zA-Z0-9]+$",message="字段必須爲英文或數字")
@Size(min=1,max=20,message="{username.size}")
message="{username.size}"這種可將message放在resource 目錄下提示信息配置文件“ValidationMessages.properties“中(名字必須爲“ValidationMessages.properties“ 因爲SpringBoot自動讀取classpath中的ValidationMessages.properties文件名):
username.size=用戶名必須在1到20字符之間
注意:
1.默認使用ISO8859-1解碼,解碼得到的字符串是亂碼,解決:ValidationMessages.properties文件編碼設置爲UTF-8,new String(error.getDefaultMessage().getBytes("ISO8859-1"), "UTF-8")。
2.min、max指的是字符長度,不是字節長度。