首页 > 代码库 > 如何在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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。