在输入控制器之前如何修改请求参数(@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。
我会错过什么吗?如果无法工作,是否有更好的解决方案?
最佳答案
解决的办法是删除@RequestParam
,谢谢Sotirios Delimanolis!