@PathVariable Validation in Spring 4

How can I check my path variable in spring. I want to check the id field, since its only one field does not want to move to Pojo

@RestController public class MyController { @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public ResponseEntity method_name(@PathVariable String id) { /// Some code } } 

I tried adding confirmation to the path variable, but 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 } } 
+6
source share
3 answers

You need to create a bean in the Spring configuration:

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

You must leave the @Validated annotation on your controller.

And you need an Exception handler in your MyController class to handle a 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(); } 

After these changes, you will see your message when the check is verified.

PS: I just tried this with your @Size check.

+12
source

I think this is a problem @RequestMapping("/") so Add @RequestMapping("/") to the rest class, then use @pathVariable

 @RestController @RequestMapping("/xyz") public class MyController { @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public ResponseEntity method_name(@PathVariable String id) { /// Some code } } 
0
source

To archive this goal, I applied this workaround to get a response message equal to the real Validator :

 @GetMapping("/check/email/{email:" + Constants.LOGIN_REGEX + "}") @Timed public ResponseEntity isValidEmail(@Email @PathVariable(value = "email") String email) { return userService.getUserByEmail(email).map(user -> { Problem problem = Problem.builder() .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE) .withTitle("Method argument not valid") .withStatus(Status.BAD_REQUEST) .with("message", ErrorConstants.ERR_VALIDATION) .with("fieldErrors", Arrays.asList(new FieldErrorVM("", "isValidEmail.email", "not unique"))) .build(); return new ResponseEntity(problem, HttpStatus.BAD_REQUEST); }).orElse( new ResponseEntity(new UtilsValidatorResponse(EMAIL_VALIDA), HttpStatus.OK) ); } 
0
source

All Articles