在 Jersey 2 中可以这样做:
@GET
@PATH("user/{email}")
public IDto getUser(@NotNull @Email @PathParam("email") String validEmail) {
return userManagementService.findUserByEmail(validEmail);
}
但是我无法在 Spring MVC 中进行类似的工作,似乎只有在 @RequestBody 中提供对象或使用 SpringMVC Form 时才会进行验证,例如以下内容将不起作用:
@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
。
这是一个示例。
根据OP的问题,这应该有效:
@RestController
@Validated
public class MyController {
@GetMapping(value="/user/{email}")
public @ResponseBody IDto getUser(@NotNull @Email @PathVariable String validEmail) {
return userManagementService.findUserByEmail(validEmail);
}
}
在普通的 Spring 实现中,可能需要手动注册验证器 bean:
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
@Validated
注释即可。@NotBlank
、@Min(1)
等)放在方法签名中的@RequestParam
注释之前。控制器应使用 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 + "";
}
据我所知,你不能用 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