一尘不染

Spring 4中的@PathVariable验证

spring-boot

我如何在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
    }
}

阅读 539

收藏
2020-05-30

共1个答案

一尘不染

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

 @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
         return new MethodValidationPostProcessor();
    }

您应该将@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();
    }

进行这些更改之后,您将在验证成功时看到您的消息。

PS:我只是在您的@Size验证下尝试过。

2020-05-30