spring boot參數校驗實踐簡單總結

1.傳遞的參數是json類型或者以實體對象傳遞的

A. 在實體類的屬性上添加校驗註解

public class User {

  
  @NotNull(message = "{the userName is not null}")
  private Long userId;
  
  private String userName;

  //get/set方法省略
}


B.在controller層的方法的參數前面添加@Valid註解

public Result<Boolean> update(@RequestBody @Valid User user) throws Exception {
 
}

2.單個參數校驗

A.controller層的方法裏面,對應參數前面直接添加註解。

B. 並拋出異常,單獨自定義一個統一異常處理器,對參數校驗的一場進行處理。(統一異常處理參考上一篇博客)

 public Result<List<User>> selectById(
     @NotNull(message = "{validator.constraints.NotNull.userId}") @RequestParam("userId") Long userId)
      throws Exception {
   
  }

3.參數是對象,但是在不同的方法裏,參數校驗的需求不同。比如兩個請求,一個請求需要對Id和name兩個字段進行校驗,而另一個方法只需要對id做校驗。

傳統方式:針對不同請求,單獨對不同請求下的參數進行校驗。

A.在實體類的屬性校驗註解中使用groups屬性

public class User {
  @NotNull(groups=ID.class,message = "{the userId is not null}")
  private Long userId;

  @NotBlack(groups=NAME.class,message = "{the userName is not null}")
  private String userName;

  //get/set方法省略
  
  public interface NAME{};
  public interface ID{};
}

B.在controller層中按照不同請求標註

@RequestMapping(value="testName")
  public void testName(@Validated(NAME.class) User user) {
  }
  @RequestMapping(value="testNameandId")
  public void testNameandId(@Validated({NAME.class,ID.class})
      User user) {
  }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章