Java 如何避免弹簧';s参数类型检查/转换?
嗨,我正在尝试使用SpringAOP构建我自己的参数提取器+验证器 首先,我定义了如下请求映射:Java 如何避免弹簧';s参数类型检查/转换?,java,spring,spring-mvc,spring-aop,Java,Spring,Spring Mvc,Spring Aop,嗨,我正在尝试使用SpringAOP构建我自己的参数提取器+验证器 首先,我定义了如下请求映射: @RequestMapping(value = "/hello", method = RequestMethod.GET) public void ttt(@MyParam(method = CheckMethod.LONG_TIMESTAMP) Long mparam) { // do something here System.out.println(mparam); } 以及
@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方法识别参数名,并尝试将参数映射(和类型转换)到相应的参数中,即使我没有为参数声明任何Spring注释。例如,“/hello?mparam=jwoijf”将简单地返回一个默认的tomcat 400错误,描述“客户端发送的请求在语法上不正确”,并且有警告级别的调试日志表明spring无法将字符串“jwijf”转换为长值。那么如何避免这种Spring特性呢
我不想使用@modeldattribute
和@Valid
方法来提取参数并验证它们的原因是:
实际上,让参数具有相同的名称和不同类型的值不是一个好主意。好吧,似乎我可以添加RequestParam(required=false),但我真的不想为每个参数添加两个注释(RequestParam和MyParam)…@KenBekov是的,你是对的,它们不是不同的类型,而是不同的验证策略,例如,搜索用户的“mode”参数允许在1到3之间,但搜索项的“mode”参数仅允许在1到2之间。因此,您基本上希望围绕框架工作,并且放弃适当的OO和spring默认工作方式(您不能再教他们spring MVC,因为您现在有自己的解决方案)。不要使用AOP来创建您自己的
HandlerMethodArgumentResolver
,它知道如何处理该注释。@M.Deinum谢谢!我想这基本上就是我需要的!实际上,让参数具有相同的名称和不同类型的值不是一个好主意。好吧,似乎我可以添加RequestParam(required=false),但我真的不想为每个参数添加两个注释(RequestParam和MyParam)…@KenBekov是的,你是对的,它们不是不同的类型,而是不同的验证策略,例如,搜索用户的“mode”参数允许在1到3之间,但搜索项的“mode”参数仅允许在1到2之间。因此,您基本上希望围绕框架工作,并且放弃适当的OO和spring默认工作方式(您不能再教他们spring MVC,因为您现在有自己的解决方案)。不要使用AOP来创建您自己的HandlerMethodArgumentResolver
,它知道如何处理该注释。@M.Deinum谢谢!我想这基本上就是我需要的!