@RequestParam與@NotBlank、@NotNull驗證注解,需不需要同時使用?
前言
在Controller中可能會同時出現(xiàn)@RequestParam和驗證注解(@NotBlank、@NotNull等),那么同時使用以哪種驗證為準呢?
一、使用步驟
1.@RequestParam和驗證注解同時使用
代碼如下:
@RequestMapping("/test")
public String test(
@RequestParam(required = false, defaultValue = "")
@NotBlank(message = "用戶名不能為空") String name)
return "success";
}
說明:
(1)如果url請求中有傳參數(shù),只需要驗證@NotBlank;
(2)如果url請求中沒有傳參數(shù),@RequestParam中只要有defaultValue,不管required是true還是false,參數(shù)的值都賦為defaultValue的值,再驗證@NotBlank;
例:@ReuqstParam(required=true, defaulfValue="張三") @NotBlank(message="用戶名不能為空") String name此時沒有傳參,name為張三,雖然required值為true,但是不會報錯。
(3)如果@RequestParam中required屬性為true,沒有defaultValue且url請求中沒有傳參,那么會返回@RequestParam的錯誤信息,不會返回@NotBlank的錯誤信息。
例:@RequestParam(required=true) @NotBlank(message = "用戶名不能為空") String name此時沒有傳參,只會返回@RequestParam沒有參數(shù)的錯誤。
注意:沒有傳參與沒有參數(shù)值是有區(qū)別的,required限制的是url中有這個參數(shù),參數(shù)的值是多少并不關心,如果沒有值,會被賦值為null;@NotBlank限制的是參數(shù)的值不能為空(null或去除空白符長度為0)。沒有傳參,required=true時會報錯,沒有參數(shù)值,@NotBlank會報錯。
2.@RequestParam和驗證注解單獨使用
@RequestParam:
@RequestMapping("/test")
public String test(
@RequestParam String name)
return "success";
}
說明:@RequestParam默認為true必填,這時候如果不傳就會報錯
Required String parameter 'name' is not present
這時候的錯誤提示是英文的,不是很友好。
@NotBlank:
@RequestMapping("/test")
public String test(
@NotBlank(message = "用戶名不能為空") String name)
return "success";
}
說明:這時候報錯信息就是message定義的錯誤
test.name: 用戶名不能為空
這時候的提示信息就比較友好,可以全局異常捕捉,封裝后返回提示信息給前端:
總結
如果參數(shù)不需要默認值,使用@NotBlank、@NotNull驗證注解比較友好。
原文鏈接:https://blog.csdn.net/u011974797/article/details/125654371