当前位置:   article > 正文

为@RequestMapping标注的方法扩展其传入参数

add a "method" parameter to this "@requestmapping" annotation

从Spring3.1开始有了HandlerMethodArgumentResolver接口,可以为@RequestMapping标注的方法扩展其传入参数。

首先,自定义注解CurrentUser

  1. @Target({ElementType.PARAMETER})
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. public @interface CurrentUser {
  5. /**
  6. * 当前用户在request中的名字 默认user
  7. *
  8. * @return
  9. */
  10. String value() default "user";
  11. }

然后,实现HandlerMethodArgumentResolver接口

  1. import org.springframework.core.MethodParameter;
  2. import org.springframework.web.bind.support.WebDataBinderFactory;
  3. import org.springframework.web.context.request.NativeWebRequest;
  4. import org.springframework.web.method.support.HandlerMethodArgumentResolver;
  5. import org.springframework.web.method.support.ModelAndViewContainer;
  6. public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
  7. public CurrentUserMethodArgumentResolver() {
  8. }
  9. @Override
  10. public boolean supportsParameter(MethodParameter parameter) {
  11. if (parameter.hasParameterAnnotation(CurrentUser.class)) {
  12. return true;
  13. }
  14. return false;
  15. }
  16. @Override
  17. public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
  18. CurrentUser currentUserAnnotation = parameter.getParameterAnnotation(CurrentUser.class);
  19. return webRequest.getAttribute(currentUserAnnotation.value(), NativeWebRequest.SCOPE_REQUEST);
  20. }
  21. }

在Spring-MVC的配置文件中加入以下配置:

  1. <mvc:annotation-driven>
  2. <mvc:argument-resolvers>
  3. <bean class="xx.xx.xx.CurrentUserMethodArgumentResolver" />
  4. </mvc:argument-resolvers>
  5. </mvc:annotation-driven>

这样,你就可以在有@RequestMapping标注的的方法中使用了,如

  1. @RequestMapping(value = "index")
  2. public String index(@CurrentUser User user, Model model) {
  3. System.out.println(user.getUsername());
  4. return "admin/index";
  5. }

 

转载于:https://my.oschina.net/shitou2016/blog/711951

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/310136
推荐阅读
  

闽ICP备14008679号