如何在 Spring 验证我的路径变量。我想验证 id 字段,因为它唯一的单个字段我不想移动到 Pojo
@RestController
public class MyController {
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseEntity method_name(@PathVariable String id) {
/// Some code
}
}
我尝试向路径变量添加验证,但仍然无法正常工作
@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
}
}
最佳答案
你需要在你的 Spring 配置中创建一个 bean:
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
您应该在 Controller 上保留 @Validated
注释。
您需要在 MyController
类中使用 Exceptionhandler 来处理ConstraintViolationException
:
@ExceptionHandler(value = { ConstraintViolationException.class })
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public String handleResourceNotFoundException(ConstraintViolationException e) {
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
StringBuilder strBuilder = new StringBuilder();
for (ConstraintViolation<?> violation : violations ) {
strBuilder.append(violation.getMessage() + "\n");
}
return strBuilder.toString();
}
进行这些更改后,您应该会在验证成功时看到您的消息。
P.S.:我刚刚通过您的 @Size
验证进行了尝试。
关于spring - Spring 4 中的@PathVariable 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35403744/