How to validate request in SOAP Spring Web Services using annotations

Viewed 548

I've developed a SOAP web service using SpringBoot and want to validate my request parameters like empty, length, min, max, etc. using annotation based approach and want to return the appropriate error message to the client.

I tried to make use of hibernate-validator with @Valid annotation and custom exceptionHandlers but it doesn't seems to be working for SOAP service. It's working fine for REST service.

Can you please suggest how can we achieve this in SOAP service.

1 Answers

When developing a SOAP service, validation is generally done using an XSD schema. But if you like to use Bean Validation, you could always trigger it manually. Roughly, something like this:

public abstract class SelfValidating<T> {
    private final Validator validator;

    public SelfValidating() {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

    public void validate() {
        Set<ConstraintViolation<T>> violations = validator.validate((T) this);
        if (!violations.isEmpty()) {
            throw new MyValidationException(violations, (MyDTO) this);
        }
    }
}

Put validation annotations (@NotEmpty and so on) you need on the instance fields of your class.

public class MyDTO extends SelfValidating<MyDTO> {
}

Then you can trigger validation by invoking myDTO.validate() anywhere you like, and handle the exception in a global exception handler.

Related