简体   繁体   中英

How to validate request in SOAP Spring Web Services using annotations

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM