1. 程式人生 > 程式設計 >SpringBoot使用jsr303校驗的實現

SpringBoot使用jsr303校驗的實現

依賴新增

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

一些較老版本的SpringBoot需要新增相關依賴,我使用的2.1.4發行版不用這個操作。

驗證使用物件接收引數的情況

public class PointDeductSetRequest {
 private Long id;
 @NotBlank(message = "租戶id為空")
 private String tenantId;
 private Integer status;
 @NotNull
 private Integer pointValue;
 @NotNull
 private Integer deductValue;
 @NotBlank(message = "操作員id為空")
 private String operator;
}

首先在需要驗證的物件的對應欄位上方加上校驗註解,以下為一些常用註解:

  • @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格式
@RequestMapping(value = "/deduct",method = RequestMethod.POST)
public BusinessResponse setPointDeduct(@RequestBody @Valid PointDeductSetRequest request){
  pointDeductService.setPointDeductRule(request);
  return new BusinessResponse(ResponseEnum.OK);
}

之後在controller方法的物件引數前加@Valid註解。

校驗使用單個引數接受的情況

@RequestMapping(value = "/deduct",method = RequestMethod.GET)
public PageResponse<TPointDeduct> getPointDeductList(@RequestParam(value = "page",required = false) Integer page,@RequestParam(value = "pageSize",required = false) Integer pageSize,@RequestParam(value = "tenantId",required = false) @NotBlank(message = "租戶id為空") String tenantId,@RequestParam(value = "status",required = false) Integer status){
  PageResponse<TPointDeduct> response = pointDeductService.getPointDeductList(page,pageSize,tenantId,status);
 response.setCodeMsg(ResponseEnum.OK);
 return response;
}

首先需要在controller類上加@Validated註解,之後在方法中需要校驗的引數前加上對應的校驗註解進行校驗。

對校驗產生的異常的捕獲

定義全域性異常處理類並用@ControllerAdvice標註,由於物件和單個引數因校驗產生的異常型別不同,因此需要分別處理。

對於物件作為接收前端請求的情況,因校驗產生的異常型別為MethodArgumentNotValidException,示例方法如下:

/**
 * 捕獲303對於body中的物件欄位校驗
 * @param e
 * @param request
 * @return
 */@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
ResponseEntity<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e,HttpServletRequest request){
  List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
 if (fieldErrors != null && !fieldErrors.isEmpty()){
   String message = fieldErrors.get(0).getDefaultMessage();
 log.error(message,e);
 }
  HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
 HttpHeaders headers = new HttpHeaders();
 Response response = new Response();
 response.setCode(ResponseEnum.FORMAT_ERROR.code());
 response.setMessage(ResponseEnum.FORMAT_ERROR.message());
 return new ResponseEntity<>(response,headers,httpStatus);
}

對於使用單個引數接受前端請求,因校驗產生的異常類為ConstraintViolationException,示例方法如下:

/**
 * 捕獲303對於request param單個引數的校驗
 * @param e
 * @param request
 * @return
 */@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
ResponseEntity<Object> handleConstraintViolationException(ConstraintViolationException e,HttpServletRequest request){
  HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
 HttpHeaders headers = new HttpHeaders();
 Response response = new Response();
 response.setCode(ResponseEnum.FORMAT_ERROR.code());
 response.setMessage(ResponseEnum.FORMAT_ERROR.message());
 return new ResponseEntity<>(response,httpStatus);
}

到此這篇關於SpringBoot使用jsr303校驗的實現的文章就介紹到這了,更多相關SpringBoot jsr303校驗內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!