很多人在使用Spring的過程中不是太注重細節。此文章主要涉及validation在Spring Boot中的使用問題,對於初入spring boot的人還是值得參考的。
轉自
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}")