I would like to write custom annotations, that would modify Spring request or path parameters according to annotations. 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 :
@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 ?
@RequestParam is a Spring annotation used to bind a web request parameter to a method parameter. It has the following optional elements: defaultValue - used as a fallback when the request parameter is not provided or has an empty value. name - name of the request parameter to bind to.
Spring Boot made passing parameters easy with Java annotations. In the above URL, there are two parameters which are v and t. To pass the parameters, put “?”. Then, add the parameter name followed by “=” and the value of the parameter.
In Spring MVC, the @RequestParam annotation is used to read the form data and bind it automatically to the parameter present in the provided method. So, it ignores the requirement of HttpServletRequest object to read the provided data.
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
@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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With