spring boot @PathVariable无法验证

时间:2017-10-25 03:10:14

标签: spring validation spring-boot

是的,与@PathVariable Validation in Spring 4Add class level validation to @Pathvariable in Spring

相同的问题

spring验证不适用于param,不会抛出异常,这里是我的代码跟随@Patrick的回答,对他而言

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

/**
 * 
 * @param accountId
 */
@RequestMapping(value="/orderDetailSelByAccountId/{accountId}.json",method= {RequestMethod.POST})
@ResponseBody
@Validated
public Result<?> orderDetailSelByAccountId(  @NotNull @NotBlank 
@Size(min=10,max=32)@PathVariable(value="accountId") String accountId) { ....    }

但是当我发送null accountId时,没有异常抛出... 我是对的,还有其他解决方案吗?

3 个答案:

答案 0 :(得分:4)

在为我工作的中添加以下注释(而不是方法

@Validated

答案 1 :(得分:1)

设置一个名为MethodValidationPostProcessor的bean

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

并将@Validated设置为控制器类,

@Validated

然后,如果要在控制器建议中正确捕获它们,请将此代码放入控制器建议中。

@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();
}

答案 2 :(得分:1)

我知道这个问题已经很老了,但只是在 Spring Boot v2.4.5 中偶然发现了同样的问题。所有其他反应对某些灭绝都是正确的,我想在这里澄清一下。 正如 subin-chalil 正确提到的,@Validated 必须放在类级别,此注释的处理由 MethodValidationPostProcessor 完成,这使我们通过 mafei 来回答。 但是,使用 Spring Boot,您基本上可以添加相应的实现作为依赖项,以便它可以成为类路径的方式。 例如添加:

    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
    </dependency>

为以下代码段启用验证逻辑

@Validated
@RestController
@RequestMapping(path = GreetingResource.BASE_PATH)
public class GreetingResource {

     static final String BASE_PATH = "/greet";
     static final String HELLO_PATH = "/hello";

    @GetMapping
    @RequestMapping(path = HELLO_PATH + "/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, String> greet(@Size(min = 1, max = 5) @PathVariable String name) {
        return Collections.singletonMap("response", String.format("Hi %s !", name));
    }

处理 GET 请求:/greet/hello/Testyy 导致 javax.validation.ConstraintViolationException

{"timestamp":"2021-05-10T15:13:05.863+00:00","status":500,"error":"Internal Server Error","trace":"javax.validation.ConstraintViolationException: greet.name: size must be between 1 and 5 ...