parameter拦截器

拦截一些非法的参数信息,使用注解的方式

mport java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;



public class ParameterValidateInterceptor implements MethodInterceptor {

private static Log logger = LogFactory
.getLog(ParameterValidateInterceptor.class);

private boolean isExpectedParamValue(Annotation[] annotations,
Object[] params, int index) {
if (annotations != null && annotations.length > 0) {
for (Annotation annotation : annotations) {
if (annotation instanceof ParamValueValidator) {
ParamValueValidator validatorAnnotation = (ParamValueValidator) annotation;
if (String.class.isAssignableFrom(validatorAnnotation.classType()))
return !StringUtil.isEmpty((String)params[index]);
if (Integer.class.isAssignableFrom(validatorAnnotation
.classType()))
return (Integer) params[index] > 0;
if (Long.class.isAssignableFrom(validatorAnnotation
.classType()))
return (Long) params[index] > 0;
if (Collection.class.isAssignableFrom(validatorAnnotation
.classType()))
return params[index] != null
&& !((Collection>) params[index]).isEmpty();

}
}
}
return true;
}
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		Object[] params = invocation.getArguments();
		if (params != null && params.length > 0) {
			Annotation[][] annotationss = invocation.getMethod()
					.getParameterAnnotations();
			if (annotationss == null || annotationss.length == 0)
				return invocation.proceed();
			for (int i = 0; i < annotationss.length; i++) {
				Annotation[] annotations = annotationss[i];
				if (!isExpectedParamValue(annotations, params, i)) {
					String methodName = " [" + invocation.getMethod().getDeclaringClass().getName() + "." + invocation.getMethod().getName() + "] ";
					logger.debug(methodName + "the parameter value isn't as we expected,null/empty is return.");

					if (Collection.class.isAssignableFrom(invocation
							.getMethod().getReturnType()))
						return Collections.emptyList();

					if (Map.class.isAssignableFrom(invocation.getMethod()
							.getReturnType()))
						return Collections.emptyMap();
					return null;
				}
			}
		}
		return invocation.proceed();
	}

 

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface ParamValueValidator {
	
	Class<?> classType();

}

 

 

你可能感兴趣的:(parameter)