Springboot?hibernate-validator?6.x快速校驗(yàn)示例代碼
一、版本信息及maven依賴
hibernate-validator 7.x版本有問題,暫時(shí)以6.2.1.Final為例,6.2.1.Final版本解決了Log4j版本的漏洞
<properties>
<!-- JDK版本 -->
<java.version>1.8</java.version>
<!-- 構(gòu)建時(shí)編碼 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 輸出時(shí)編碼 -->
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<hutool.version>5.7.16</hutool.version>
<hibernate-validator.version>6.2.1.Final</hibernate-validator.version>
</properties>
記得引入:spring-boot-starter-validation
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
二、定義實(shí)體bean
import javax.validation.constraints.Email;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import org.hibernate.validator.constraints.Length;
public class User {
private Integer id;
@Min(18)
@Max(200)
private Integer age;
@NotBlank(message = "姓名不能為空")
@Length(min = 2, max = 6, message = "長(zhǎng)度必須在{min}和{max}個(gè)字符之間")
private String name;
@NotBlank(message = "電子郵箱不能為空")
@Email(message = "電子郵箱格式不正確")
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User [id=" + id + ", age=" + age + ", name=" + name + ", email=" + email + "]";
}
}
三、測(cè)試Controller
需要在類上面加上注解:@Validated
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Validated
public class UserController {
@RequestMapping("/get")
public User get(@NotNull(message = "id不能為空") Integer id,
@NotNull(message = "姓名不能為空") String name) {
User user = new User();
user.setName("lisi");
user.setId(id);
return user;
}
@RequestMapping("/save")
public User get(@Valid User user) {
return user;
}
}
四、hibernate-validator全局異常處理
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalException {
public static final String DELIM = ",";
@ExceptionHandler(Exception.class)
@ResponseBody
public String exceptionHandler(HttpServletRequest request, HttpServletResponse response,
Exception e) {
if(e instanceof ConstraintViolationException) {
//@RequestParam上參數(shù)validate失敗后拋出的異常
ConstraintViolationException cve = (ConstraintViolationException) e;
Set<ConstraintViolation<?>> violations = cve.getConstraintViolations();
StringBuffer sb = new StringBuffer("");
for (ConstraintViolation<?> constraintViolation : violations) {
sb.append(constraintViolation.getMessage()).append(DELIM);
}
if(sb.indexOf(DELIM) > -1) {
sb.deleteCharAt(sb.length() - 1);
}
System.out.println("ConstraintViolationException sb="+sb);
response.setStatus(HttpStatus.BAD_REQUEST.value());
return sb.toString();
}else if(e instanceof BindException) {
//@RequestParam上實(shí)體對(duì)象validate失敗后拋出的異常
BindException be = (BindException) e;
System.out.println("be.getMessage()="+be.getMessage());
List<FieldError> fieldErrors = be.getBindingResult().getFieldErrors();
StringBuffer sb = new StringBuffer("");
for (FieldError fieldError : fieldErrors) {
sb.append(fieldError.getDefaultMessage()).append(DELIM);
//System.out.println("fieldError.getDefaultMessage() =" + fieldError.getDefaultMessage());
}
if(sb.indexOf(DELIM) > -1) {
sb.deleteCharAt(sb.length() - 1);
}
System.out.println("BindException sb="+sb);
response.setStatus(HttpStatus.BAD_REQUEST.value());
return sb.toString();
}else if(e instanceof MethodArgumentNotValidException) {
//@RequestBody上validate失敗后拋出的異常
MethodArgumentNotValidException mave = (MethodArgumentNotValidException) e;
System.out.println("mave.getMessage() = " + mave.getMessage());
List<FieldError> fieldErrors = mave.getBindingResult().getFieldErrors();
StringBuffer sb = new StringBuffer("");
for (FieldError fieldError : fieldErrors) {
sb.append(fieldError.getDefaultMessage()).append(DELIM);
//System.out.println("fieldError.getDefaultMessage() =" + fieldError.getDefaultMessage());
}
if(sb.indexOf(DELIM) > -1) {
sb.deleteCharAt(sb.length() - 1);
}
System.out.println("MethodArgumentNotValidException sb="+sb);
response.setStatus(HttpStatus.BAD_REQUEST.value());
return sb.toString();
}
return "系統(tǒng)異常";
}
}
五、hibernate-validator快速校驗(yàn)
hibernate-validator默認(rèn)會(huì)全部校驗(yàn)后再返回所有錯(cuò)誤結(jié)果,為了讓hibernate-validator檢查到第一個(gè)錯(cuò)誤馬上返回結(jié)果,需要配置快速校驗(yàn)
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.hibernate.validator.HibernateValidator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
@Configuration
public class ValidatorConfiguration {
/**
* 快速返回校驗(yàn)器
* @return
*/
@Bean
@ConditionalOnMissingBean(value = Validator.class)
public Validator validator() {
//hibernate-validator 6.x沒問題,7.x有問題
ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
.configure()
.failFast(true)
//.addProperty("hibernate.validator.fail_fast", "true")
.buildValidatorFactory();
return validatorFactory.getValidator();
}
/**
* 設(shè)置快速校驗(yàn),返回方法校驗(yàn)處理器
* @return
*/
@Bean
@ConditionalOnMissingBean(value = MethodValidationPostProcessor.class)
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
postProcessor.setValidator(validator());
return postProcessor;
}
}
到此這篇關(guān)于Springboot?hibernate-validator?6.x校驗(yàn)的文章就介紹到這了,更多相關(guān)Springboot?hibernate?validator?校驗(yàn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot參數(shù)校驗(yàn)Validator框架詳解
- springboot中validator數(shù)據(jù)校驗(yàn)功能的實(shí)現(xiàn)
- springboot表單提交之validator校驗(yàn)
- springboot validator枚舉值校驗(yàn)功能實(shí)現(xiàn)
- SpringBoot 使用hibernate validator校驗(yàn)
- springboot使用Validator校驗(yàn)方式
- springboot使用hibernate validator校驗(yàn)方式
- SpringBoot使用Validator進(jìn)行參數(shù)校驗(yàn)實(shí)戰(zhàn)教程(自定義校驗(yàn),分組校驗(yàn))
相關(guān)文章
Springboot如何設(shè)置過濾器及重復(fù)讀取request里的body
這篇文章主要介紹了Springboot如何設(shè)置過濾器及重復(fù)讀取request里的body,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
idea與eclipse項(xiàng)目相互導(dǎo)入的過程(圖文教程)
這篇文章主要介紹了idea與eclipse項(xiàng)目相互導(dǎo)入的過程,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
Spring基于xml實(shí)現(xiàn)自動(dòng)裝配流程詳解
自動(dòng)裝配是使用spring滿足bean依賴的一種方法,spring會(huì)在應(yīng)用上下文中為某個(gè)bean尋找其依賴的bean,Spring中bean有三種裝配機(jī)制,分別是:在xml中顯式配置、在java中顯式配置、隱式的bean發(fā)現(xiàn)機(jī)制和自動(dòng)裝配2023-01-01
Spring Aop組成部分及實(shí)現(xiàn)步驟
面向切面編程,是對(duì)面向?qū)ο缶幊痰囊环N補(bǔ)充,是一種編程思想,是對(duì)某一類的事情的集中處理,這篇文章主要介紹了Spring Aop組成部分及實(shí)現(xiàn)步驟,需要的朋友可以參考下2023-08-08
springboot controller參數(shù)注入方式
這篇文章主要介紹了springboot controller參數(shù)注入方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05

