• 如何在Spring Boot 中使用 HandlerMethodArgumentResolver


    本例子是使用HandlerMethodArgumentResolver方便的获取session中的内容。

    SessionInfo.java 在session中存储用户数据

    ...
    public class SessionInfo { private Integer userId; private String username; private String ua; private String ip; ...//constructors,setters and getters }

      

    SessionInfoArgumentResolver.java HandlerMethodArgumentResolver 的实现类

    ...
    @Component
    public class SessionInfoArgumentResolver implements HandlerMethodArgumentResolver {
        @Override
        public boolean supportsParameter(MethodParameter methodParameter) {
            return methodParameter.getParameterType().equals(SessionInfo.class);
        }
    
        @Override
        public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer mavContainer,
                                      NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
            String attrName = "sessionInfo";
            Object sessionInfo = webRequest.getAttribute(attrName, RequestAttributes.SCOPE_SESSION);
            if (sessionInfo == null) {
                //实例化
                sessionInfo = new SessionInfo(-1);
                HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
                HttpSession session = request.getSession();
                session.setAttribute(attrName, sessionInfo);
            }
            return sessionInfo;
        }
    }
    

      

    Application.java 程序启动器

    ...
    @SpringBootApplication
    public class Application extends WebMvcConfigurerAdapter {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
        @Override
        public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
            super.addArgumentResolvers(argumentResolvers);
            argumentResolvers.add(new SessionInfoArgumentResolver());
        }
    }
    

      

    TestRestController.java 测试用的控制器

    @RestController
    @RequestMapping("test")
    public class TestRestController {
    
        @RequestMapping("t1")
        public String t1(SessionInfo sessionInfo) {
            return "" + sessionInfo.getUserId();
        }
    }
    

      

    测试成功

  • 相关阅读:
    Python3 获取抖音无水印视频 2020年12月23日----lanyi原创
    javascript9分享到菜单,菜单在屏幕左侧的移出和收回
    javascript8图片刹车运动
    javascript7图片的淡入淡出
    javascript6鼠标拖拽图片
    javascript5每秒改变字体颜色的大小
    javascript4动态生成表格
    javascript3跟随鼠标的提示框
    javascript2选项卡
    同学,为什么Golang中不用this和self
  • 原文地址:https://www.cnblogs.com/parasis/p/6389101.html
Copyright © 2020-2023  润新知