[英]Custom Spring annotation for request parameters
I would like to write custom annotations, that would modify Spring request or path parameters according to annotations. 我想编写自定义注释,根据注释修改Spring请求或路径参数。 For example instead of this code:
例如,而不是这段代码:
@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 ? 它是否可能,如果是,我怎么能这样做?
As the guys said in the comments, you can easily write your annotation driven custom resolver. 正如这些人在评论中所说,你可以轻松编写注释驱动的自定义解析器。 Four easy steps,
四个简单的步骤,
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UpperCase {
String value();
}
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();
}
}
<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());
}
...
}
public String test(@UpperCase("foo") String foo)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.