b/s系統中對http請求數據的校驗多數在客戶端進行,這也是出於簡單及用戶體驗性上考慮,但是在一些安全性要求高的系統中服務端校驗是不可缺少的。
Spring3支持JSR-303驗證框架,JSR-303 是Java EE 6 中的一項子規范,叫做BeanValidation,官方參考實現是hibernate Validator(與Hibernate ORM 沒有關系),JSR 303 用於對Java Bean 中的字段的值進行驗證。
validation與 springboot 結合
1. bean 中添加標簽
部分代碼:
標簽需要加在屬性上,@NotBlank 標簽含義文章末尾有解釋
public class User { private Integer id; @NotBlank(message = "{user.name.notBlank}") private String name; private String username;
2. Controller中開啟驗證
在Controller 中 請求參數上添加@Validated 標簽開啟驗證
@RequestMapping(method = RequestMethod.POST) public User create(@RequestBody @Validated User user) { return userService.create(user); }
3. resource 下新建錯誤信息配置文件
在resource 目錄下新建提示信息配置文件“ValidationMessages.properties“
注意:名字必須為“ValidationMessages.properties“ 因為SpringBoot自動讀取classpath中的ValidationMessages.properties里的錯誤信息
ValidationMessages.properties 文件的編碼為ASCII。數據類型為 key value 。key“user.name.notBlank“為第一步 bean的標簽 大括號里面對應message的值
value 為提示信息 ,但是是ASCII 。(內容為“名字不能為空“)
4. 自定義異常處理器,捕獲錯誤信息
當驗證不通過時會拋異常出來,異常的message 就是 ValidationMessages.properties 中配置的提示信息。此處定義異常處理器。捕獲異常信息(因為驗證不通過的項可能是多個所以統一捕獲處理),並拋給前端。(此處是前后端分離開發)
public void MethodArgumentNotValidException(Exception ex, HttpServletRequest request, HttpServletResponse response) { logger.error( ":" + CommonUtil.getHttpClientInfo(request), ex); MethodArgumentNotValidException c = (MethodArgumentNotValidException) ex; List<ObjectError> errors =c.getBindingResult().getAllErrors(); StringBuffer errorMsg=new StringBuffer(); errors.stream().forEach(x -> errorMsg.append(x.getDefaultMessage()).append(";")); pouplateExceptionResponse(response, HttpStatus.INTERNAL_SERVER_ERROR, errorMsg.toString()); } private void pouplateExceptionResponse(HttpServletResponse response, HttpStatus errorCode, String errorMessage) { try { response.sendError(errorCode.value(), errorMessage); } catch (IOException e) { logger.error("failed to populate response error", e); } }
5. 附上部分標簽含義
限制 | 說明 |
---|---|
@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,也可以通過正則表達式和flag指定自定義的email格式 |
示例
@Pattern(regexp="^[a-zA-Z0-9]+$",message="{account.username.space}") @Size(min=3,max=20,message="{account.username.size}")