如何在进入控制器之前修改请求参数(@RequestParam String bar
)?
理想情况下,我想创建一个注释:
@RequestMapping(method = GET, path = "foo")
public ResponseEntity<String> getBar(@RequestParam @Sanitize("bar") String bar) {
// bar is sanitized
/** method body *//
}
根据to this question,我尝试创建界面Sanitize
:
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface Sanitize {
String value();
}
解析器SanitizeResolver
public class SanitizeResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterAnnotation(Sanitize.class) != null;
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
Sanitize attr = parameter.getParameterAnnotation(Sanitize.class);
return MyUtils.sanitize(webRequest.getParameter(attr.value()));
}
}
并将解析器添加到WebMvcConfigurerAdapter
的解析器中:
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new SanitizeResolver());
}
解析器添加良好,但从未调用过。
我正在使用Spring 4.2.6.RELEASE。 我是否会遗漏某些内容,如果无法解决问题,是否有更好的解决方案?
答案 0 :(得分:0)
解决方案是删除@RequestParam
,感谢Sotirios Delimanolis!