首頁 > 軟體

SpringBoot引數校驗之@Validated的使用詳解

2022-06-28 14:03:04

簡介

說明

本文用範例說明SpringBoot的@Validated的用法。

依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

它裡邊依賴了hibernate validator,就是下邊這個

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
</dependency>

用法1:不分組

跟上邊“@Valid範例”的結果是一樣的,只是把入參處的@Valid改為@Validated。

程式碼

Controller

package com.example.demo.validated.without_group.controller;
 
import com.example.demo.validated.without_group.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.validation.Valid;
import java.util.List;
 
@Api(tags = "不分組")
@RestController
@RequestMapping("validatedWithoutGroup")
public class ValidatedWithoutGroupController {
 
    @ApiOperation("正常用法")
    @GetMapping("normal")
    public User normal(@Validated User user) {
        return user;
    }
 
    @ApiOperation("獲得BindingResult")
    @GetMapping("bindingResult")
    public User bindingResult(@Validated User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            List<ObjectError> list = bindingResult.getAllErrors();
            for (ObjectError objectError : list) {
                System.out.println(objectError.getDefaultMessage());
            }
            //System.out.println(bindingResult.getFieldError().getDefaultMessage());
        }
 
        return user;
    }
 
}

Entity

User類

package com.example.demo.validated.without_group.entity;
 
import lombok.Data;
 
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
 
@Data
public class User {
    @NotBlank(message = "名字不能為空")
    private String name;
 
    private Integer age;
 
    @NotBlank(message = "密碼不能為空")
    private String password;
 
    @NotEmpty(message = "分數不能為空")
    private List<Integer> scoreArray;
 
    @Valid
    @NotNull(message = "賬戶不能為null")
    private Account account;
}

Account類

package com.example.demo.validated.without_group.entity;
 
import lombok.Data;
 
import javax.validation.constraints.NotBlank;
 
@Data
public class Account {
    @NotBlank(message = "電話號碼不能為空")
    private String phoneNumber;
 
    private String[] emails;
}

測試

測試1:缺少欄位

postman存取:http://localhost:8080/validatedWithoutGroup/normal

postman結果:

後端結果:

2021-12-22 16:12:26.549  WARN 79176 --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 3 errors
Field error in object 'user' on field 'scoreArray': rejected value [null]; codes [NotEmpty.user.scoreArray,NotEmpty.scoreArray,NotEmpty.java.util.List,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.scoreArray,scoreArray]; arguments []; default message [scoreArray]]; default message [分數不能為空]
Field error in object 'user' on field 'password': rejected value [null]; codes [NotBlank.user.password,NotBlank.password,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.password,password]; arguments []; default message [password]]; default message [密碼不能為空]
Field error in object 'user' on field 'account': rejected value [null]; codes [NotNull.user.account,NotNull.account,NotNull.com.example.demo.validated.without_group.entity.Account,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.account,account]; arguments []; default message [account]]; default message [賬戶不能為null]]

測試2:不缺少欄位

postman存取:http://localhost:8080/validatedWithoutGroup/normal

postman結果:

測試3: 獲得BindingResult

postman存取:http://localhost:8080/validatedWithoutGroup/bindingResult

postman結果:

後端結果:

分數不能為空
密碼不能為空
賬戶不能為null

用法2:分組

程式碼

Controller

package com.example.demo.validated.with_group.controller;
 
import com.example.demo.validated.with_group.entity.User;
import com.example.demo.validated.with_group.validatation.IGroupA;
import com.example.demo.validated.with_group.validatation.IGroupAll;
import com.example.demo.validated.with_group.validatation.IGroupB;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
 
import java.util.List;
 
@Api(tags = "分組")
@RestController
@RequestMapping("validatedWithGroup")
public class ValidatedWithGroupController {
    @ApiOperation("使用組:GroupA")
    @GetMapping("groupA")
    public User groupA(@Validated({IGroupA.class}) User user) {
        return user;
    }
 
    @ApiOperation("使用組:GroupB")
    @GetMapping("groupB")
    public User groupB(@Validated({IGroupB.class}) User user) {
        return user;
    }
 
    @ApiOperation("使用組:GroupA和GroupB")
    @GetMapping("groupAAndGroupB")
    public User groupAAndGroupB(@Validated({IGroupA.class, IGroupB.class}) User user) {
        return user;
    }
 
    @ApiOperation("使用組:GroupAll")
    @GetMapping("groupAll")
    public User groupAll(@Validated({IGroupAll.class}) User user) {
        return user;
    }
 
}

Entity

User類

package com.example.demo.validated.with_group.entity;
 
import com.example.demo.validated.with_group.validatation.IGroupA;
import com.example.demo.validated.with_group.validatation.IGroupB;
import lombok.Data;
 
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
 
@Data
public class User {
    @NotBlank(message = "名字不能為空")
    private String name;
 
    @NotNull(message = "年齡不能為空", groups = {IGroupA.class})
    private Integer age;
 
    @NotEmpty(message = "密碼不能為空", groups = {IGroupB.class})
    private String password;
 
    @NotEmpty(message = "分數不能為空", groups = {IGroupA.class, IGroupB.class})
    private List<Integer> scoreArray;
 
    @Valid
    @NotNull(message = "賬戶不能為null")
    private Account account;
}

Account類

package com.example.demo.validated.with_group.entity;
 
import lombok.Data;
 
import javax.validation.constraints.NotEmpty;
 
@Data
public class Account {
    @NotEmpty(message = "電話號碼不能為空")
    private String phoneNumber;
 
    private String[] emails;
}

Group

IGroupA介面

package com.example.demo.validated.with_group.validatation;
 
public interface IGroupA {
}

IGroupB介面 

package com.example.demo.validated.with_group.validatation;
 
public interface IGroupB {
}

IGroupAll介面 

package com.example.demo.validated.with_group.validatation;
 
import javax.validation.GroupSequence;
import javax.validation.groups.Default;
 
@GroupSequence({Default.class, IGroupA.class, IGroupB.class})
public interface IGroupAll {
}

測試

測試1:無引數請求groupA

postman存取:http://localhost:8080/validatedWithGroup/groupA

postman結果:

後端結果:

2021-12-22 16:32:44.138  WARN 85532 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'user' on field 'scoreArray': rejected value [null]; codes [NotEmpty.user.scoreArray,NotEmpty.scoreArray,NotEmpty.java.util.List,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.scoreArray,scoreArray]; arguments []; default message [scoreArray]]; default message [分數不能為空]
Field error in object 'user' on field 'age': rejected value [null]; codes [NotNull.user.age,NotNull.age,NotNull.java.lang.Integer,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.age,age]; arguments []; default message [age]]; default message [年齡不能為空]]

測試2:無引數請求groupB

postman存取:http://localhost:8080/validatedWithGroup/groupB

postman結果:

後端結果:

2021-12-22 16:33:15.773  WARN 85532 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'user' on field 'scoreArray': rejected value [null]; codes [NotEmpty.user.scoreArray,NotEmpty.scoreArray,NotEmpty.java.util.List,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.scoreArray,scoreArray]; arguments []; default message [scoreArray]]; default message [分數不能為空]
Field error in object 'user' on field 'password': rejected value [null]; codes [NotEmpty.user.password,NotEmpty.password,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.password,password]; arguments []; default message [password]]; default message [密碼不能為空]]

測試3:無引數請求groupA和groupB

postman存取:http://localhost:8080/validatedWithGroup/groupAAndGroupB

postman結果:

後端結果:

2021-12-22 16:34:27.652  WARN 85532 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 3 errors
Field error in object 'user' on field 'scoreArray': rejected value [null]; codes [NotEmpty.user.scoreArray,NotEmpty.scoreArray,NotEmpty.java.util.List,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.scoreArray,scoreArray]; arguments []; default message [scoreArray]]; default message [分數不能為空]
Field error in object 'user' on field 'age': rejected value [null]; codes [NotNull.user.age,NotNull.age,NotNull.java.lang.Integer,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.age,age]; arguments []; default message [age]]; default message [年齡不能為空]
Field error in object 'user' on field 'password': rejected value [null]; codes [NotEmpty.user.password,NotEmpty.password,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.password,password]; arguments []; default message [password]]; default message [密碼不能為空]]

測試4:無引數請求groupAll

postman存取:http://localhost:8080/validatedWithGroup/groupAll

postman結果:

後端結果:

2021-12-22 16:36:54.095  WARN 91820 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'user' on field 'name': rejected value [null]; codes [NotBlank.user.name,NotBlank.name,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.name,name]; arguments []; default message [name]]; default message [名字不能為空]
Field error in object 'user' on field 'account': rejected value [null]; codes [NotNull.user.account,NotNull.account,NotNull.com.example.demo.validated.with_group.entity.Account,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.account,account]; arguments []; default message [account]]; default message [賬戶不能為null]]

可以看到:走的校驗邏輯是沒有除了IGroupA和IGroupB註解的欄位的邏輯。

以上就是SpringBoot引數校驗之@Validated的使用詳解的詳細內容,更多關於SpringBoot引數校驗@Validated的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com