Java – Custom spring annotations for request parameters
•
Java
I want to write a custom annotation that will modify the spring request or path parameters according to the annotation 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 can comment @ uppercase:
@RequestMapping(method = RequestMethod.GET)
public String test(@RequestParam("title") @UpperCase String text) {
System.out.println(text);
return "form";
}
Is it possible? If so, what should I do?
Solution
As people say in comments, you can easily write your annotation - driven custom parser Four simple steps,
>Create a comment, for example
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UpperCase {
String value();
}
>Write a parser, for example
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 parser
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="your.package.UpperCaseResolver"></bean>
</mvc:argument-resolvers>
</mvc:annotation-driven>
Or Java configuration
@Configuration
@EnableWebMvc
public class Config extends WebMvcConfigurerAdapter {
...
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new UpperCaseResolver());
}
...
}
>Use annotations in controller methods, such as
public String test(@UpperCase("foo") String foo)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
