自從ssm框架火起來以後,ssh框架也就不再被人青睞,同樣的hibernate似乎已經成了歷史, 但是這幾天我發現hibernate框架居然用在了我們公司的代碼中,所以趕緊研究了一下.
配合代碼來介紹
1. 依賴
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
2. 接收前段傳過來的參數的Dto類
import javax.validation.constraints.NotNull;
private class UserReqDto{
@NotNull(message = "用戶名不能爲空")
private String userName;
@NotNull(message = "密碼不能爲空")
private String password;
@NotNull(message = "聯繫地址不能爲空")
private String address;
@NotNull(message = "電話號碼不能爲空")
private String phone;
...getter and setter...
}
2.控制層
@Controller
public class Test {
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test(@Valid @RequestBody UserReqDto userDto){
//service的邏輯...
}
這個時候如果直接發起請求,UserReqDto 其中一個字段爲null,就會報錯, 如果userName=null
...arguments []; default message [userName]]; default message [用戶名不能爲空]]
如果想要或者這個message信息,可以通過Spring的@ExceptionHandler和@ControllerAdvice
統一處理異常
參數校驗失敗,會經過spring的org.springframework.web.bind.MethodArgumentNotValidException
異常類拋出異常,我們處理這個異常類的信息就可以了
@ControllerAdvice
@ResponseBody
public class ExceptionHandle {
private static final Logger log = LoggerFactory.getLogger(ExceptionHandle.class);
public ExceptionHandle() {
}
@ExceptionHandler({MethodArgumentNotValidException.class})
public String handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
BindingResult result = e.getBindingResult();
FieldError error = result.getFieldError();
String field = error.getField();
String code = error.getDefaultMessage();
String message = String.format("%s:%s", field, code);
log.warn("參數驗證失敗:" + message);
return "參數驗證失敗:" + message;
}
}
彈出的顯示信息:
2018-08-14 17:54:27.673 WARN com.zgd.exception.ExceptionHandle Line:124 - 參數驗證失敗:mchtName:mchtName不能爲空
3. 其他的valid註解
hibernate除了JSR303的標準之外還額外提供了其他的驗證註解。下表是JSR303支持的驗證註解:
hibernate-validator附帶的註解
4. group分組
比如name,password,age在登錄的時候,需要name和password不爲空, 在修改年齡的時候,僅需要age不爲空, 所以在不同的需求中, 校驗也不一樣, 這個時候我們可以分組
@NotNull(message = "用戶名不能爲空", groups = GroupA.class)
private String userName;
@NotNull(message = "密碼不能爲空", groups = GroupB.class)
private String password;
這個時候我們需要自定義沒有方法的接口:
public interface GroupA {
}
public interface GroupB {
}
然後在方法中指定我們需要哪個group的校驗就可以了
public String test(@Validated(GroupA.class) @RequestBody UserReqDto dto){
}
這個時候將
{"userName":null,"password":null}
作爲參數進行訪問,只會報用戶名不能爲空