@PathVariable Validation in Spring 4

前端 未结 2 1210
清酒与你
清酒与你 2020-12-08 22:24

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
publi         


        
相关标签:
2条回答
  • 2020-12-08 23:04

    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.

    0 讨论(0)
  • 2020-12-08 23:08

    To archive this goal I have apply this workaround for getting a response message equals to a 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 讨论(0)
提交回复
热议问题