ras*_*orp 5 java spring spring-mvc
在泽西岛2,可以这样做:
@GET
@PATH("user/{email}")
public IDto getUser(@NotNull @Email @PathParam("email") String validEmail) {
return userManagementService.findUserByEmail(validEmail);
}
Run Code Online (Sandbox Code Playgroud)
但我无法在Spring MVC中创建类似的东西,似乎验证只在@RequestBody中提供对象或使用SpringMVC表单时完成,例如以下操作无效:
@RequestMapping(value="/user/{email}", method = RequestMethod.GET)
public @ResponseBody IDto getUser(@NotNull @Email @PathVariable String validEmail) {
return userManagementService.findUserByEmail(validEmail);
}
Run Code Online (Sandbox Code Playgroud)
还有其他类似的问题,但那些似乎是面向Spring MVC UI应用程序,在我的情况下,它只是一个返回JSON响应的REST API,因此我没有任何View映射/绑定到控制器.
看起来这是可能的,使用@Validated.
这是一个例子。
根据OP的问题,这应该有效:
@RestController
@Validated
public class MyController {
@GetMapping(value="/user/{email}")
public @ResponseBody IDto getUser(@NotNull @Email @PathVariable String validEmail) {
return userManagementService.findUserByEmail(validEmail);
}
}
Run Code Online (Sandbox Code Playgroud)
在普通的 Spring 实现中,可能需要手动注册验证器 bean:
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
Run Code Online (Sandbox Code Playgroud)
据我所知,你不能用 Spring 来做到这一点。
选项:
使用正则表达式:
@RequestMapping(value="/user/{email:SOME_REXEXP}", method = RequestMethod.GET)
public @ResponseBody IDto getUser(@PathVariable String validEmail) {
return userManagementService.findUserByEmail(validEmail);
}
Run Code Online (Sandbox Code Playgroud)使用 Hibernate Validator 来验证该方法。要么手动调用验证器,要么让 Spring 使用 AOP 为您调用它。请参阅https://github.com/gunnarmorling/methodvalidation-integration
| 归档时间: |
|
| 查看次数: |
5447 次 |
| 最近记录: |