spring bootにおけるデータ検証validatedの使用

8128 ワード

前言
spring-bootではController層の中で@validatedでデータを検査してから業務ロジック層に入ることができます.データが異常であれば統一的に異常を投げます.異常センターで一括処理しやすいです.例えば、入力されたユーザー名の長さ制限とパスワードの正則検証を判断します.
使用プロセス
1.ontroller層データ使用@validated注释
@PostMapping("/userLogin")
@ResponseBody
public TResult login(@RequestBody(required=true) @Validated User user) {
    return  accountServiceInter.login(user);
  }
}
2次にmodelで検証が必要なフィールドを宣言します.
@Pattern(regexp = "^[a-zA-Z0-9_]{4,16}$", message = "     4-16 ")
	private String username;
	//    
	@Pattern(regexp ="^[a-zA-Z0-9_]{6,16}$", message = "     6-16 ")
	private String password;
3.すべて異常捕獲
 /**
     *             
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public TResult handleValidException(MethodArgumentNotValidException  e) {
        logger.error("      ",e);
        TResult tResult = TResultEncap.setErrResult(ReturnCodeBase.ERR6000);
        tResult.setErrMsg(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return tResult;
    }
入力が条件を満たしていない場合は異常を投げて異常センターで処理することを推奨します.これを使うとマニュアルで異常を処理し、正常な論理過程に侵入します.
常用注釈の種類
 @AssertFalse   false
@AssertTrue   true
@DecimalMax(value=,inclusive=)     value,
inclusive=true,     
@DecimalMin(value=,inclusive=)     
@Max(value=)     value
@Min(value=)     value
@NotNull    Null
@Past      
@Pattern(regex=,flag=)    
@Size(min=, max=)     ,  ,map    
@Validate  po       
ネストチェック
一つのクラスにもう一つの実体類が含まれているなら、上に@Validatedを付ければいいです.
 public class Student{    
    @validated
    private List< User>studentList;
 }