0

There is a controller accepting code as a path variable

@RestController
@RequestMapping(value = "/api/currency")
@Validated
public class CurrencyController {

    @GetMapping("/gif/{code}")
    public ResponseEntity<Map> getChangeGif(@PathVariable @Code String code){
        // some implementation
        return null;
    }
}

I want to use my own annotation to validate code as I want

@Target( { FIELD, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy =  CodeValidator.class)
public @interface Code {

    public String message() default "error message";

    public Class<?>[] groups() default {};

    public Class<? extends Payload>[] payload() default {};
}

And here is the validator

public class CodeValidator implements ConstraintValidator<Code, String> {
    @Override
    public void initialize(Code constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(String code, ConstraintValidatorContext context) {
        // validator implementation
        return false;
    }
}

For some reason when requests come, validation just skipps, and controller continue working without it

2
  • See stackoverflow.com/questions/19419234/… Commented Jun 1, 2022 at 10:35
  • This code is working fine. See if you are missing anything in project. Try first with standard validation like @Length(min=2) etc Commented Jun 1, 2022 at 11:03

1 Answer 1

0

Just a wild guess, since you asked specifically for @PathVariable validation and I just stumbled upon this myself:

If you are in a real life project, you might also have an authorization check that prevents the validation. The typical order the validation and pre-authorize checks in spring are done are the following and maybe not intuitive:

  1. Validation of @RequestBody parameter
  2. Performing @PreAuthorize check
  3. Validation of @PathVariable parameter

So it happened to me that I thought the path variable validation was not working in contrast to the request body validation - but it was simply covered by the authorization check ;-)

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

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.