Search code examples
springvalidationdwrdata-transfer-objects

How do I validate my DWR @RemoteMethod input objects?


I’m using DWR 3.0.0-rc2 and Spring 3.1.1.RELEASE.  I was wondering if its possible to validate my @DataTransferObject input object using the Spring style “@Valid” (javax.validation.Valid) annotation.  My specific question is, if this is possible and I set up my remote call like so …

@RemoteMethod
@Override
public String myRemoteMethod(@Valid final MyDto request)
{

how do I test to see if the input object (request) is valid and then throw a corresponding set of errors back to the client? Thanks, - Dave


Solution

  • This looks like a good case to apply some AOP. One way is to create a @Before aspect that inspects the called arguments to see if they are annotated with @Valid, and if so trigger the validation for that argument and treat the results.

    The code of this aspect would look like this:

    @Aspect
    public class ValidatingAspect {
    
        Validator validator;
    
        public ValidatingAspect() {
            Configuration<?> configuration = Validation.byDefaultProvider().configure();
            ValidatorFactory factory = configuration.buildValidatorFactory();
            this.validator = factory.getValidator();    
        }
    
        @Before("execution(* com.yourpackage..*.*(..))")
        public void validateBefore(JoinPoint jp) throws Throwable {
            Object[] args = jp.getArgs();
            MethodSignature ms = (MethodSignature) jp.getSignature();
            Method m = ms.getMethod();
    
            Annotation[][] parameterAnnotations = m.getParameterAnnotations();
    
            for (int i = 0; i < parameterAnnotations.length; i++) {
                Annotation[] annotations = parameterAnnotations[i];
                for (Annotation annotation : annotations) {
                    if (annotation.annotationType() == Valid.class) {
                        Set<ConstraintViolation<T>> constraintViolations =  validator.validate(jp.getArgs()[i]); 
                           ... handle validation results ...
                    }
                }
            }
        } 
    }