zoukankan      html  css  js  c++  java
  • springMVC自定义方法属性解析器

    使用场景例子:

    用户登陆系统一般会往Session里放置一个VO对象,然后在controller里会来获取用户的userId等信息。

    之前的写法是:@SessionAttributes配合@ModelAttribute来进行参数值的注入,但这样需要写2个注解,其中SessionAttributes加在类上,ModelAttribute加在方法的属性上。

    SpringMVC提供了HandlerMethodArgumentResolver接口来处理我们的自定义参数的解析。

    例子:

    1、获取用户信息的注解类

    复制代码
    import java.lang.annotation.*;
    
    /**
     * <p>绑定当前登录的用户</p>
     * <p>不同于@ModelAttribute</p>
     */
    @Target({ElementType.PARAMETER})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface CurrentUser {
    
        /**
         * 当前用户在request中的名字
         *
         * @return
         */
        String value() default "loginUser";
    
    }
    复制代码

    2、自定义的参数解析器

    复制代码
    import com.gongren.cxht.pay.web.shiro.bind.annotation.CurrentUser;
    import org.springframework.core.MethodParameter;
    import org.springframework.web.bind.support.WebDataBinderFactory;
    import org.springframework.web.context.request.NativeWebRequest;
    import org.springframework.web.method.support.HandlerMethodArgumentResolver;
    import org.springframework.web.method.support.ModelAndViewContainer;
    
    /**
     * <p>自定义方法参数解析器
     */
    public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
    
        public CurrentUserMethodArgumentResolver() {
        }
    
        @Override
        public boolean supportsParameter(MethodParameter parameter) {
            if (parameter.hasParameterAnnotation(CurrentUser.class)) {
                return true;
            }
            return false;
        }
    
        @Override
        public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
            CurrentUser currentUserAnnotation = parameter.getParameterAnnotation(CurrentUser.class);
            //从session的scope里取CurrentUser注解里的value属性值的key的value
            return webRequest.getAttribute(currentUserAnnotation.value(), NativeWebRequest.SCOPE_SESSION);
        }
    }
    复制代码

    3、将自定义的解析器加入springmvc的配置文件里

    <mvc:annotation-driven>
         <mvc:argument-resolvers>
            <!-- SESSION USER -->
            <bean class="com.test.CurrentUserMethodArgumentResolver"/>
        </mvc:argument-resolvers>
    </mvc:annotation-driven>

    在controller里的使用方法:

    @RequestMapping(value = "/test")
    public String test(@CurrentUser AccUserVo user) {
        
    }
  • 相关阅读:
    多线程与多进程
    Socket网络编程
    Python之路【第五篇】:面向对象及相关
    python 面向对象(进阶篇)
    面向对象
    day1
    day3
    day2
    黑马程序员--C语言中的指针(6)
    黑马程序员--C语言中的指针(5)
  • 原文地址:https://www.cnblogs.com/moxiaotao/p/9629249.html
Copyright © 2011-2022 走看看