How can i validate my path variable in spring. I want to validate id field, since its only single field i do not want to move to a Pojo
@RestController
public class MyController {
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseEntity method_name(@PathVariable String id) {
/// Some code
}
}
I tried doing adding validation to the path variable but its still not working
@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
}
}
You need to create a bean in your Spring configuration:
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
You should leave the @Validated
annotation on your controller.
And you need an Exceptionhandler in your MyController
class to handle theConstraintViolationException
:
@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();
}
After those changes you should see your message when the validation hits.
P.S.: I just tried it with your @Size
validation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With