Spring 4中的@PathVariable验证 [英] @PathVariable Validation in Spring 4
问题描述
我如何在春季验证我的路径变量.我想验证id字段,因为我不想将其移至Pojo
How can i validate my path variable in spring. I want to validate id field, since its only single field i do not want to move to a Pojo
@RestController
public class MyController {
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseEntity method_name(@PathVariable String id) {
/// Some code
}
}
我尝试在路径变量中添加验证,但是它仍然不起作用
I tried doing adding validation to the path variable but its still not working
@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:
You need to create a bean in your Spring configuration:
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
您应该在控制器上保留@Validated
批注.
You should leave the @Validated
annotation on your controller.
并且您在MyController
类中需要一个Exceptionhandler来处理ConstraintViolationException
:
And you need an Exceptionhandler in your MyController
class to handle theConstraintViolationException
:
@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();
}
进行这些更改后,当验证成功时,您应该会看到消息.
After those changes you should see your message when the validation hits.
P.S .:我刚刚在您的@Size
验证中尝试过.
P.S.: I just tried it with your @Size
validation.
这篇关于Spring 4中的@PathVariable验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!