请求参数的自定义Spring注释 [英] Custom Spring annotation for request parameters

查看:127
本文介绍了请求参数的自定义Spring注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写自定义注释,根据注释修改Spring请求或路径参数。例如,代替此代码:

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";
}

我可以注释@UpperCase:

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 ?

推荐答案

正如大家在评论中所说,你可以轻松编写注释驱动的自定义解析器。四个简单的步骤,

As the guys said in the comments, you can easily write your annotation driven custom resolver. Four easy steps,


  1. 创建注释,例如







@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UpperCase {
    String value();
}




  1. 写一个解析器,例如







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();
    }
}




  1. 注册一个解析器







<mvc:annotation-driven>
        <mvc:argument-resolvers>
            <bean class="your.package.UpperCaseResolver"></bean>
        </mvc:argument-resolvers>
</mvc:annotation-driven>

或java config

or the java config

    @Configuration
    @EnableWebMvc
    public class Config extends WebMvcConfigurerAdapter {
    ...
      @Override
      public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
          argumentResolvers.add(new UpperCaseResolver());
      }
    ...
    }




  1. 在控制器方法中使用注释,例如







public String test(@UpperCase("foo") String foo) 

这篇关于请求参数的自定义Spring注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆