uyl*_*lmz 6 java spring spring-validator spring-rest
有没有办法使用注释验证原始(int,String等)GET参数?
@RequestMapping(value = "/api/{someInt}",
method = RequestMethod.GET,
produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> someRestApiMethod(
@PathVariable
@Valid @Min(0) @Digits(integer=10, fraction=0)
int someInt) {
//...
return new ResponseEntity<String>("sample:"+someInt, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
如你所见,我已经放了一堆注释来验证someInt是一个10位数的正整数,但它仍接受各种整数.
是的,这是可能的.
给出以下控制器:
@RestController
@Validated
public class ValidatingController {
@RequestMapping("/{id}")
public int validatedPath(@PathVariable("id") @Max(9) int id) {
return id;
}
@ExceptionHandler
public String constraintViolationHandler(ConstraintViolationException ex) {
return ex.getConstraintViolations().iterator().next()
.getMessage();
}
}
Run Code Online (Sandbox Code Playgroud)
并MethodValidationPostProcessor在您的上下文中注册如下(或等效的XML,而不是Spring Boot Web启动程序 - 它将为您执行此操作):
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
Run Code Online (Sandbox Code Playgroud)
假设您的调度程序servlet映射到http://localhost:8080/:
http://localhost:8080/9给出9http://localhost:8080/10给出must be less than or equal to 9在将来的Spring版本中,似乎正在采取措施使这更容易/更自动化.
| 归档时间: |
|
| 查看次数: |
5035 次 |
| 最近记录: |