在Spring's MVC中,如果我有一個控制器,并且我想拒絕任何帶有queryparam或requestbody的請求,這些請求的字段帶有前導或尾隨空格,那么最好的方法是什么?我們能用驗證器嗎?
@PostMapping(value="/add")
public ResponseEntity<User> addUser(@Validated(AddUser.class) @Requestbody User user, BindingResult result) {
...
// Business logic here
// How to check leading and trailing spaces and throw error if present
...
return responseEntity;
}
在上面的例子中,假設User只有firstName和lastName兩個字段,我想檢查firstName和lastName沒有任何前導空格或尾隨空格,如果有,拋出錯誤,最好的方法是什么?
您可以構建自己的自定義驗證程序批注:
然后你可以用
@NoSpace
注釋你的屬性