[英]How should I validate dependent parameters in @requestparam in spring Rest API?
[英]Is it possible to validate @RequestParam in Spring MVC REST endpoint?
在 Jersey 2 中可以這樣做:
@GET
@PATH("user/{email}")
public IDto getUser(@NotNull @Email @PathParam("email") String validEmail) {
return userManagementService.findUserByEmail(validEmail);
}
但是我無法在 Spring MVC 中進行類似的工作,似乎只有在 @RequestBody 中提供對象或使用 SpringMVC 表單時才會進行驗證,例如以下內容不起作用:
@RequestMapping(value="/user/{email}", method = RequestMethod.GET)
public @ResponseBody IDto getUser(@NotNull @Email @PathVariable String validEmail) {
return userManagementService.findUserByEmail(validEmail);
}
還有其他類似的問題,但這些問題似乎是針對 Spring MVC UI 應用程序的,在我的情況下,它只是一個返回 JSON 響應的 REST API,所以我沒有任何視圖可以映射/綁定到控制器。
似乎有可能,使用@Validated
。
這是一個例子。
據我所知,你不能用 Spring 開箱即用。
選項:
使用正則表達式:
@RequestMapping(value="/user/{email:SOME_REXEXP}", method = RequestMethod.GET) public @ResponseBody IDto getUser(@PathVariable String validEmail) { return userManagementService.findUserByEmail(validEmail); }
使用 Hibernate Validator 來驗證方法。 要么手動調用驗證器,要么讓 Spring 使用 AOP 為您調用它。 見https://github.com/gunnarmorling/methodvalidation-integration
1- 只需在類的頂部添加 @Validated 注釋。 2- 在方法簽名中的 @RequestParam 注釋之前放置任何用於驗證的注釋(@NotBlank、Min(1) 等)。
控制器應使用 spring 的@Validated
進行注釋
所以更新你的代碼
@Validated
@RequestMapping(value="/user/{email}", method = RequestMethod.GET)
public @ResponseBody IDto getUser(
@NotNull
@Email
@PathVariable String validEmail) {
return userManagementService.findUserByEmail(validEmail);
}
來自org.springframework.validation.annotation.Validated
包的經過驗證的注解來驗證@PathVariable
。 確保使用@Validated
注釋的類。
@GetMapping("/name-for-day/{dayOfWeek}")
public String getNameOfDay(@PathVariable("dayOfWeek") @Min(1) @Max(7) Integer dayOfWeek) {
return dayOfWeek + "";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.