用户信息绑定会话,怎样才可以在服务层注入?
谢谢邀请回答。
如果不想在controller拿到用户信息传到service层,直接在service层也是可以拿到的。
spring mvc在处理请求的时候,会把请求对象放到RequestContextHolder持有的ThreadLocal对象中,你可以去看看DispatcherServlet类的源代码。
在service层可以按照如下代码获取:
//获取到当前线程绑定的请求对象
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
//已经拿到session,就可以拿到session中保存的用户信息了。
System.out.println(request.getSession().getAttribute("userInfo"));
SecurityContextHolder 可以处理登录用户的存取,
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource()
.buildDetails(httpRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
UsernamePasswordAuthenticationToken authentication = SecurityContextHolder.getContext().getAuthentication();
什么RequestContextHolder, shiro啊这些, 你不看源码相信用起来不会安心的, 还是自己写靠谱且简洁, 原理就是使用ThreadLocal这个技术, 以前后端分离的项目(java只是接口, 不渲染界面)为例, 流程我简单说下:
tip: 有@Async注解的方法不能用, 因为新建立了一个Thread, 这种异步方法获取用户信息只能参数传递进来
相信源码你就不需要了吧, 如果不明白的话, 使劲学习一下ThreadLocal就可以了, 记得给我设置为最佳答案