Spring 4中的@PathVariable验证

R.A*_*.S. 12 spring spring-mvc spring-security spring-data spring-boot

如何在spring中验证我的路径变量.我想验证id字段,因为它只有单个字段我不想移动到Pojo

@RestController
public class MyController {
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResponseEntity method_name(@PathVariable String id) {
        /// Some code
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试在路径变量中添加验证,但它仍然无效

    @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
    }
}
Run Code Online (Sandbox Code Playgroud)

Pat*_*ick 18

您需要在Spring配置中创建一个bean:

 @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
         return new MethodValidationPostProcessor();
    }
Run Code Online (Sandbox Code Playgroud)

您应该将@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();
    }
Run Code Online (Sandbox Code Playgroud)

完成这些更改后,您应该在验证命中时看到您的消息.

PS:我刚试过你的@Size验证.