如何在春季驗證我的路徑變量。我想驗證id字段,因爲其唯一單場我不想要移動到一個POJO@PathVariable Spring 4中的驗證
@RestController
public class MyController {
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseEntity method_name(@PathVariable String id) {
/// Some code
}
}
我試圖做添加驗證到PATH變量,但它仍然沒有工作
@RestController
@Validated
public class MyController {
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseEntity method_name(
@Valid
@Nonnull
@Size(max = 2, min = 1, message = "name should have between 1 and 10 characters")
@PathVariable String id) {
/// Some code
}
}
在你的代碼中沒有路徑變量,至少不在你的URL中,所以不知道什麼需要驗證... –
對不起,我錯過了它w hile在這裏複製和粘貼代碼 –
你可以嘗試簡單if循環method_name方法if(id == null || id.length()<1 || id.length()> 2){String message =「name應該有1到10個字符」; }如果循環結果爲真,您可以按照您的要求返回ResponseEntity, –