'Access Headers at any time when implementing org.springframework.validation.Validator

I have a Spring Boot Application where I need to perform some validation over the request's fields based on a header value.

So like any other Spring Boot App my entry point in my rest controller looks like

public ResponseEntity<Mono<MyResponse>> myOperation(MyRequest request, String another_parameter)

My problem here is, in order to perform my validations I was thinking on using org.springframework.validation.Validator

Whenever you want to implement above Interface, you have to do something like:

public class WebsiteUserValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return MyRequest.class.equals(clazz);
    }

    @Override
    public void validate(Object obj, Errors errors) {
        MyRequest user = (MyRequest) obj;
        if (checkInputString(MyRequest.getSomeField())) {
            errors.rejectValue("someField", "someField.empty");
        }
    }

    private boolean checkInputString(String input) {
        return (input == null || input.trim().length() == 0);
    }
}

I would like to get the headers in the validate method implementations.

How to achieve that? (get the headers at any time so to speak).



Solution 1:[1]

I think use javax.validation.ConstraintValidator<A extends Annotation, T> will better. for example the Annotation

@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy ={SexConstraintValidator.class} )
public @interface Sex {
    //default error message
    String message() default "default error message";
    //groups
    Class<?>[] groups() default {};
    //payload
    Class<? extends Payload>[] payload() default {};
}

SexConstraintValidator

public class SexConstraintValidator implements ConstraintValidator<Sex,String> {

    @Override
    public void initialize(Sex constraintAnnotation) {

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        boolean isValid =doSomeValided();
        return isValid;
    }

}

validate object

public class ValidateObject {

    @Sex(message="error message")
    private String sex;

    // ...
}

the validate method

import org.springframework.validation.annotation.Validated;
public ResponseEntity<Mono<MyResponse>> myOperation(@Validated ValidateObject request, String another_parameter)

or validate manual like this

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Set<ConstraintViolation<ValidateObject>> validate=validatorFactory.getValidator().validate(validateObject);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jiang