Albert Pinto
Albert Pinto

Reputation: 402

Spring Rest Web service input validation

I have a Spring rest webservice. The controller class map the parameters in the HTTP request to a custoom Request Object. My Request object looks like this:

 public class DMSRequest_global {
     protected String userName = "";
     protected String includeInactiveUsers = "";
     protected String documentType = ""; And the getter and setter of the fields above 
 }

Spring uses reflection to set the values from the incomming request to this object.My question is is it possible for us using annotation or some thing to validate a field like documentType in the example above to only accept a value from a list of acceptable values like {".doc", ".txt",".pdf"} . If some other value is sent in the request spring will throw an invalid request exception.

Upvotes: 1

Views: 1834

Answers (1)

shazin
shazin

Reputation: 21923

You can write your own custom validator.

@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Contraint(validatedBy = DocumentTypeValidator.class)
@Documented
public @interface ValidDocumentType {

    String message() default "{com.mycompany.constraints.invaliddocument}";

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

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

    String[] value();
}

And a custom validator for that.

public class DocumentTypeValidator implements ConstraintValidator<ValidDocumentType, String> {

    private String[] extenstions;

    public void initialize(ValidDocumentType constraintAnnotation) {
        this.extenstions = constraintAnnotation.value();
    }

    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {

        if (object == null)
            return true;

        for(String ext:extenstions) {
            if(object.toLowerCase().matches(ext.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

}

Finally you can annotate your bean with the custom annotation.

@ValidDocumentType({"*.doc", "*.txt","*.pdf"})
protected String documentType = "";

You can read more about this in this post

Upvotes: 1

Related Questions