java 请求参数的自定义 Spring 注释
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30715579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom Spring annotation for request parameters
提问by arminas
I would like to write custom annotations, that would modify Spring request or path parameters according to annotations. For example instead of this code:
我想编写自定义注释,根据注释修改 Spring 请求或路径参数。例如,而不是此代码:
@RequestMapping(method = RequestMethod.GET)
public String test(@RequestParam("title") String text) {
text = text.toUpperCase();
System.out.println(text);
return "form";
}
I could make annotation @UpperCase :
我可以注释 @UpperCase :
@RequestMapping(method = RequestMethod.GET)
public String test(@RequestParam("title") @UpperCase String text) {
System.out.println(text);
return "form";
}
Is it possible and if it is, how could I do it ?
是否可能,如果可能,我该怎么做?
回答by Master Slave
As the guys said in the comments, you can easily write your annotation driven custom resolver. Four easy steps,
正如这些人在评论中所说,您可以轻松编写注释驱动的自定义解析器。四个简单的步骤,
- Create an annotation e.g.
- 创建一个注释,例如
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UpperCase {
String value();
}
- Write a resolver e.g.
- 写一个解析器,例如
public class UpperCaseResolver implements HandlerMethodArgumentResolver {
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterAnnotation(UpperCase.class) != null;
}
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) throws Exception {
UpperCase attr = parameter.getParameterAnnotation(UpperCase.class);
return webRequest.getParameter(attr.value()).toUpperCase();
}
}
- register a resolver
- 注册解析器
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="your.package.UpperCaseResolver"></bean>
</mvc:argument-resolvers>
</mvc:annotation-driven>
or the java config
或 java 配置
@Configuration
@EnableWebMvc
public class Config extends WebMvcConfigurerAdapter {
...
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new UpperCaseResolver());
}
...
}
- use an annotation in your controller method e.g.
- 在您的控制器方法中使用注释,例如
public String test(@UpperCase("foo") String foo)