vvsueprman
vvsueprman

Reputation: 143

spring boot @PathVariable can not validate

yeah, the same question as @PathVariable Validation in Spring 4 and Add class level validation to @Pathvariable in Spring

spring validated not work for param, throw no exception, here is my code follow by @Patrick's answer, thx for him

@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) { ....    }

but when I send null accountId, there are no exception throws... am I right, are there anyother solutions?

Upvotes: 1

Views: 11164

Answers (3)

fr.fish93
fr.fish93

Reputation: 31

I know the question is quite old but just stumbled across the same issue with Spring Boot v2.4.5. All other responses are correct to some extinct I'd like to bring more clarity here. As correctly mentioned by subin-chalil @Validated has to be placed on the class level, processing of this annotation is done by MethodValidationPostProcessor which brings us to answer by mafei. However with Spring Boot you can basically add a corresponding implementation as a dependency so that it could make it's way to the classpath. For example adding:

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

Enabled validation logic for following snippet

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

Processing of GET request: /greet/hello/Testyy resulted in 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 ...

Upvotes: 3

Mafei
Mafei

Reputation: 3819

set a bean called MethodValidationPostProcessor

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

and set @Validated into your controller class,

@Validated

and then if, you want catch them properly in controller advice put this code in your controller advice.

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

Upvotes: 2

Subin Chalil
Subin Chalil

Reputation: 3660

Add the following annotation to the class worked for me.(Not to the method)

@Validated

Upvotes: 10

Related Questions