如何避免Spring的参数类型检查/转换?

时间:2016-01-13 03:34:16

标签: java spring spring-mvc spring-aop

您好我正在尝试使用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方式提取参数并验证它们的原因是:

  1. 使用ModelAttribute会让我创建太多模型(模型的每个请求)。
  2. 某些模型属性是相同的,有些甚至不具有相同的名称。
  3. 队友必须知道如何限制每个属性才能创建新的ModelAttribute。

0 个答案:

没有答案