2

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?

7
  • i think @Validated should go as class level annotation according to the links you provide in the question Commented Oct 25, 2017 at 3:40
  • still not work.............. Commented Oct 25, 2017 at 4:30
  • You can validate it manually when request received in the controller. If validation failed, then send a error message. I think this should be better approach. Commented Oct 25, 2017 at 5:26
  • my project have a exception center, it can catch all exception in boot project, so I think the better way is use annotation and in the exception center to handle all the valid error Commented Oct 25, 2017 at 5:34
  • According to this answer and the related issue the annotation isn't supported for @PathVariable at the moment. Commented Oct 25, 2017 at 5:57

3 Answers 3

11

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

@Validated
Sign up to request clarification or add additional context in comments.

Comments

3

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 ...

1 Comment

By luck I came across this answer! I was missing the dependency in my pom.xml file
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.