Spring Boot使用JSR-380進行校驗的示例
JSR-380 是 J2EE 的一個規(guī)范,用于校驗實體屬性,它是 JSR-303 的升級版,在 Spring Boot 中可以基于它優(yōu)雅實現(xiàn)參數(shù)校驗。
<!--more-->
示例在沒有使用 JSR-380 之前,我們一般都會將參數(shù)校驗硬編碼在 controller 類中,示例:
public Result add(@RequestBody User user){ if(StringUtils.isBlank(user.getName())){ return Result.error('用戶名不能為空'); } // ...}
而使用 JSR-380 只需要通過添加對應的注解即可實現(xiàn)校驗,示例:
@Datapublic class User{ @NotBlank private String name; private Integer age;}
public Result register(@Validated @RequestBody User user){ // ...}
這樣看起來代碼是不是清爽了很多,只需要在需要校驗的字段上加上對應的校驗注解,然后對需要校驗的地方加上 @Validated 注解,然后框架就會幫我們完成校驗。
通過全局異常自定義錯誤響應框架校驗失敗之后會拋出異常,需要捕獲這個異常然后來自定義校驗不通過的錯誤響應,這里直接貼代碼,兼容 @RequestBody 、 @ModelAttribute 、 @RequestParam 三種入?yún)⒌男r灒?/p>
@ControllerAdvicepublic class GlobalExceptionHandler { @ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class}) public ResponseEntity<Result> methodArgumentNotValidHandler(HttpServletRequest request, Exception e) { BindingResult bindingResult; if (e instanceof MethodArgumentNotValidException) { //@RequestBody參數(shù)校驗 bindingResult = ((MethodArgumentNotValidException) e).getBindingResult(); } else { //@ModelAttribute參數(shù)校驗 bindingResult = ((BindException) e).getBindingResult(); } FieldError fieldError = bindingResult.getFieldError(); return ResponseEntity.ok(Result.fail(Result.CODE_PARAMS_INVALID, '[' + fieldError.getField() + ']' + fieldError.getDefaultMessage())); } //@RequestParam參數(shù)校驗 @ExceptionHandler(value = {ConstraintViolationException.class, MissingServletRequestParameterException.class}) public ResponseEntity<Result> constraintViolationHandler(Exception e) { String field; String msg; if (e instanceof ConstraintViolationException) { ConstraintViolation<?> constraintViolation = ((ConstraintViolationException) e).getConstraintViolations().stream().findFirst().get(); List<Path.Node> pathList = StreamSupport.stream(constraintViolation.getPropertyPath().spliterator(), false) .collect(Collectors.toList()); field = pathList.get(pathList.size() - 1).getName(); msg = constraintViolation.getMessage(); } else { // 這個不是JSR標準返回的異常,要自定義提示文本 field = ((MissingServletRequestParameterException) e).getParameterName(); msg = '不能為空'; } return ResponseEntity.ok(Result.fail(Result.CODE_PARAMS_INVALID, '[' + field + ']' + msg)); }}
然后再訪問一下接口,可以看到錯誤提示已經(jīng)按自定義的規(guī)范顯示了:
可以看到都不需要寫任何提示文本就可以完成校驗和提示,上圖的 不能為空 是框架內(nèi)置的 I18N 國際化支持,每個注解都內(nèi)置相應的提示模板。
常用校驗注解
注解 描述 @NotNull 驗證值不為 null @AssertTrue 驗證值為 true @Size 驗證值的長度介于 min 和 max 之間,可應用于 String、Collection、Map 和數(shù)組類型 @Min 驗證值不小于該值 @Max 驗證值不大于該值 @Email 驗證字符串是有效的電子郵件地址 @NotEmpty 驗證值不為 null 或空,可應用于 String、Collection、Map 和數(shù)組類型 @NotBlank 驗證字符串不為 null 并且不是空白字符 @Positive 驗證數(shù)字為正數(shù) @PositiveOrZero 驗證數(shù)字為正數(shù)(包括 0) @Negative 驗證數(shù)字為負數(shù) @NegativeOrZero 驗證數(shù)字為負數(shù)(包括 0) @Past 驗證日期值是過去 @PastOrPresent 驗證日期值是過去(包括現(xiàn)在) @Future 驗證日期值是未來 @FutureOrPresent 驗證日期值是未來(包括現(xiàn)在)
本文完整代碼放在 github 。
Java Bean Validation Basics
JSR-380 規(guī)范
到此這篇關(guān)于Spring Boot使用JSR-380進行校驗的文章就介紹到這了,更多相關(guān)Spring Boot使用JSR-380校驗內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP基礎(chǔ)入門第四篇(腳本變量、函數(shù)、過程和條件語句)2. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)3. jscript與vbscript 操作XML元素屬性的代碼4. jsp 實現(xiàn)的簡易mvc模式示例5. JSP開發(fā)之hibernate之單向多對一關(guān)聯(lián)的實例6. HTML5實戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)7. 基于PHP做個圖片防盜鏈8. Jsp servlet驗證碼工具類分享9. XML在語音合成中的應用10. php使用正則驗證密碼字段的復雜強度原理詳細講解 原創(chuàng)
