您好我正在尝试使用Spring AOP构建自己的参数提取器+验证器。
首先,我定义了一个像这样的请求映射:
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public void ttt(@MyParam(method = CheckMethod.LONG_TIMESTAMP) Long mparam) {
// do something here
System.out.println(mparam);
}
和AOP:
@Around(value = "xxx")
public Object extractAndValidate(ProceedingJoinPoint pjp) throws Throwable {
Object[] arguments = pjp.getArgs();
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
Class[] classes = method.getParameterTypes();
Annotation[][] annotations = method.getParameterAnnotations();
// get arguments whose annotation type is MyParam and get the argument name and extract it from GET request parameter or POST/PUT body
// validate all params appointed by MyParam.method, if something wrong, return user the detailed error explanation.
// if all validation has passed, then convert all parameters into appointed type, and then send them to pjp to proceed.
return pjp.proceed(arguments);
}
最大的问题是Spring自动从RequestMapping方法中识别参数名称,并尝试将GET参数映射(和类型转换)到相应的参数中,即使我没有为参数声明任何Spring注释。例如," / hello?mparam = jwoijf"将简单地返回一个默认的tomcat 400错误,描述"客户端发送的请求在语法上是不正确的。",并且有WARN级调试日志,表示spring无法转换String" jwijf"成龙值。那么我该如何避免这种Spring功能?
我不想使用@ModelAttribute
和@Valid
方式提取参数并验证它们的原因是: