4-5 获取当前线程的request请求和当前用户信息

xiaoxiao2021-02-28  44

创建 requestholder 实体类

public class RequestHolder { private static final ThreadLocal<SysUser> userHolder = new ThreadLocal<SysUser>(); private static final ThreadLocal<HttpServletRequest> requestHolder = new ThreadLocal<HttpServletRequest>(); public static void add(SysUser sysUser) { userHolder.set(sysUser); } public static void add(HttpServletRequest request) { requestHolder.set(request); } public static SysUser getCurrentUser() { return userHolder.get(); } public static HttpServletRequest getCurrentRequest() { return requestHolder.get(); } public static void remove() { userHolder.remove(); requestHolder.remove(); } }

在登录拦截器 HandlerInterceptor 添加当前请求和用户信息

public class LoginHandlerInterceptor implements HandlerInterceptor{ // 目标方法执行之前 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { SysUser sysUser= (SysUser)request.getSession().getAttribute("user"); if(sysUser == null) { // 未登陆返回登陆页面 System.out.println("-------拦截请求--------"); String path = "/test/signin"; response.sendRedirect(path); return false; }else { // 已经登陆放行请求 // 已登陆的用户加入线程当中 RequestHolder.add(sysUser); RequestHolder.add(request); return true; } } }

在需要获取当前用户的信息或请求时调用即可

sysUser.setOperator(RequestHolder.getCurrentUser().getUsername()); // 获取当前线程的用户名 sysUser.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
转载请注明原文地址: https://www.6miu.com/read-2619707.html

最新回复(0)