注解@Validated和BindingResult對入參非空校驗
在項目當中少不了入參校驗,服務器和瀏覽器互不信任,不能因為前端加入參判斷了后臺就不處理了,這樣是不對的。
比如前臺傳過來一個對象作為入參參數,這個對象中有些屬性允許為空,有些屬性不允許為空。那么你還在使用if()else{}進行非空判斷嗎?不妨嘗試下使用注解,可以使用@Validated和BindingResult。
注意:BindingResult需要放到@Validated后面
示例代碼如下:普通屬性可以用@NotEmpty() 特殊的使用@NotNull() 比如:枚舉類型
實體類:什么不允許為空就加
1
|
@NotEmpty (groups = {SchoolDTO.SchoolGroup. class },message = "學校名不能為空" ) |
注意:重要的事情叮囑兩遍。public interface SchoolGroup{} 別忘了加這個!public interface SchoolGroup{} 別忘了加這個!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public class SchoolDTO implements Serializable { private Long id; @NotEmpty (groups = {SchoolDTO.SchoolGroup. class },message = "學校名不能為空" ) private String schoolName; @NotNull @NotEmpty (groups = {SchoolDTO.SchoolGroup. class },message = "學校負責人不能為空" ) private String schoolPrincipal; @NotNull @NotEmpty (groups = {SchoolDTO.SchoolGroup. class },message = "職務不能為空" ) private String principalPosition; @NotNull @NotEmpty (groups = {SchoolDTO.SchoolGroup. class },message = "聯系電話不能為空" ) private String schoolPhone; //getter setter tostring 省略 public interface SchoolGroup{} 別忘了加這個 } |
控制層:在入參對象上加@Validated({SchoolDTO.SchoolGroup.class}), BindingResult bindingResult @Validated進行驗證,BindingResult可以獲取校驗錯誤信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@PostMapping ( "/schools" ) @PreAuthorize ( "hasRole(\"" + AuthoritiesConstants.ADMIN + "\")" ) public Map<String,Object> createSchool( @RequestBody @Validated ({SchoolDTO.SchoolGroup. class }) SchoolDTO schoolDTO,BindingResult bindingResult) throws Exception { //返回校驗錯誤信息 Map<String,Object>map= new HashMap<>(); if (bindingResult.hasErrors()){ map.put( "success" , "false" ); map.put( "message" ,bindingResult.getAllErrors()); return map; } // .........業務省略 return map; } } |
測試:入參的時候我沒有傳principalPosition和schoolPhone
@Validated 和 BindingResult 使用遇到的坑
@Validated 與BindingResult 需要相鄰,否則 變量result 不能接受錯誤信息
控制臺輸出
Field error in object 'entity' on field '變量': rejected value [null]; codes [NotNull.entity.變量,NotNull.變量,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes
正確的內容截圖
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/weixin_43770545/article/details/90237097