首页 > 代码库 > 如何在Spring Boot 中使用 HandlerMethodArgumentResolver

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

  

测试成功

技术分享

 

如何在Spring Boot 中使用 HandlerMethodArgumentResolver