關於@BindingResult bindingresult...

@PostMapping("/ownermyorderlist")
public OwnerMyOrderListResponseDTO ownerMyOrderList(@Valid @RequestBody OwnerMyOrderListRequestDTO requestDTO, BindingResult bindingResult) throws AppOrderErrorCodeException {
if (bindingResult.hasErrors()) {
throw new AppOrderErrorCodeException(bindingResult.getFieldError().getDefaultMessage());
}

return orderInfoService.ownerMyOrderList(requestDTO);
}

SpringBoot在內部經過集成hibernate-validation 已經實現了JSR-349驗證規範接口,在SpringBoot項目中只要直接使用就好了。
html

通常用在Controller中用於驗證前端傳來的參數。前端

驗證分兩種:對封裝的Bean進行驗證  或者  對方法簡單參數的驗證java

1、進行BeanValidategit

1.定義Beanspring

public class ValidBean {
    @NotNull(message = "名字不能爲空")
    private String name;

    @Min(value = 18, message = "年齡必須大於18")
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

  2.使用數組

@RequestMapping("bean")
    @ResponseBody
    public String say(@Valid ValidBean bean, BindingResult bindingResult){        
        return bindingResult.hasErrors() ? 
		bindingResult.getFieldError().getDefaultMessage() : "incorrect";
    }

3.注意
@Valid 和 BindingResult 是一一對應的,若是有多個@Valid,那麼每一個@Valid後面跟着的BindingResult就是這個@Valid的驗證結果,順序不能亂springboot

4.Api
@Null 只能是null
@NotNull 不能爲null 注意用在基本類型上無效,基本類型有默認初始值
@AssertFalse 必須爲false
@AssertTrue 必須是true

字符串/數組/集合檢查:(字符串自己就是個數組)
@Pattern(regexp="reg") 驗證字符串知足正則
@Size(max, min) 驗證字符串、數組、集合長度範圍
@NotEmpty 驗證字符串不爲空或者null
@NotBlank 驗證字符串不爲null或者trim()後不爲空

數值檢查:同時能驗證一個字符串是不是知足限制的數字的字符串
@Max 規定值得上限int
@Min 規定值得下限
@DecimalMax("10.8") 以傳入字符串構建一個BigDecimal,規定值要小於這個值 
@DecimalMin 能夠用來限制浮點數大小
@Digits(int1, int2) 限制一個小數,整數精度小於int1;小數部分精度小於int2
@Digits 無參數,驗證字符串是否合法
@Range(min=long1,max=long2) 檢查數字是否在範圍之間
這些都包括邊界值app

日期檢查:Date/Calendar
@Post 限定一個日期,日期必須是過去的日期
@Future 限定一個日期,日期必須是將來的日期

其餘驗證:
@Vaild 遞歸驗證,用於對象、數組和集合,會對對象的元素、數組的元素進行一一校驗
@Email 用於驗證一個字符串是不是一個合法的右鍵地址,空字符串或null算驗證經過
@URL(protocol=,host=,port=,regexp=,flags=) 用於校驗一個字符串是不是合法URLui

 

2、進行MethodValidate

1.注入MethodValidationPostProcessor Beanthis

@Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }

2.在要MethodValidate的類上加上註解@Validated
3.在方法中使用

     @Controller
	@Validated
	@RequestMapping("valid")
	public class ValidController {
		@RequestMapping("/check")
		@ResponseBody
		public String check(@Min(value = 2,message = "age必須大於2") int age) {
			return "" + age;
		}
	}

4.處理校驗失敗
默認校驗失敗後會讓方法拋出Unchecked Exception,在springboot中默認是會讓其跳轉到error頁面,因此只要添加一個這個異常的處理器就行:

@ExceptionHandler(value = { ConstraintViolationException.class })
    @ResponseBody
    public String handleResourceNotFoundException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        StringBuilder strBuilder = new StringBuilder();
        for (ConstraintViolation<?> violation : violations ) {
            strBuilder.append(violation.getMessage() + "\n");
        }
        return strBuilder.toString();
    } 

5.注意
若是使用了@Validated,那麼BeanValidate也會拋出異常而不是以前的封裝在BindingResult中

3、自定義異常處理
用到再查,網上不少例子

 

 

4、

驗證其實基於spring AOP ,因此其實任何Spring Bean都能利用這些註解作驗證,好比Service層。但用的最多的仍是Controller層

Spring Boot 進行Bean Validate和Metho

相關文章
相關標籤/搜索