java 您所在的位置:网站首页 查询登录 java

java

2023-07-15 20:45| 来源: 网络整理| 查看: 265

后端获取当前登录用户信息

开发过程中,发现有很多地方需要获取当前登录的用户信息,比如新增、修改时候要记录创建人和更新人信息,如果每次操作都从数据库中获取用户信息,会增加不必要的开销,同时也增加数据库的压力。

方法一: 从redis中获取

本文将介绍一种从redis缓存中获取当前登录用户的信息,实现思路如下:

用户登录时获取将用户数据存放在redis中,key值为userCode将userCode添加到cookie中后端获取cookie中的userCode,然后查询缓存,获取用户登录数据 实现代码如下: 存放用户信息到redis中, 并设置cookie /** * 存放用户信息到redis中, 并设置cookie * @param String username // 用户账号 * @return */ public static final long SESSION_TIMEOUT = Long.parseLong(prop.getProperty("session.timeout","1440000")); public static final String USER_INFO = "user_info_"; public void setUserInfoToRedis(HttpServletRequest request,String username, HttpServletResponse response){ SysUser user = userService.selectOne(new EntityWrapper().eq("LOGIN_NAME", username)); //根据登录账号查询用户信息 UserSessionModel userSessionModel = new UserSessionModel(); userSessionModel.setUser(user); // 放入缓存中 String userCode = UUIDGenerator.getUUID(); // 随机生成userCode String userKey = Constants.USER_INFO + userCode; redisUtils.set(userKey, JSON.toJSONString(userSessionModel), Constants.SESSION_TIMEOUT); // 将userCode放入cookie中 Cookie cookie = new Cookie("userCode", userCode); cookie.setPath("/"); cookie.setMaxAge((int) Constants.SESSION_TIMEOUT); response.addCookie(cookie); } 从redis中获取当前登录用户信息: public static final String USER_INFO = "user_info_"; @Autowired private HttpServletRequest request; @Autowired private RedisUtils redisUtils; /** 从redis中获取当前登录用户信息 */ public SysUser getCurrentUser() { Cookie userCookie = CookieUtil.getCookie(request, "userCode"); String userKey = Constants.USER_INFO + userCookie.getValue(); Object userInfo = redisUtils.get(userKey); UserSessionModel userSessionModel = JSON.parseObject(userInfo.toString(), UserSessionModel.class); SysUser user = userSessionModel.getUser(); return user; } 方法二: 通过Spring Security获取

Spring Security使用一个Authentication对象来描述当前用户的相关信息。SecurityContextHolder中持有的是当前用户的SecurityContext,而SecurityContext持有的是代表当前用户相关信息的Authentication的引用。这个Authentication对象不需要我们自己去创建,在与系统交互的过程中,Spring Security会自动为我们创建相应的Authentication对象,然后赋值给当前的SecurityContext。

UserDetails currentUserDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有