后端动态获取当前用户的2种获取方式

前提:(可以直接放到cookie中但是不安全,也可以每次前端请求时在请求中传输账户id ,会增加前端工作量,前后端分离后不合适)

1.利用Request、redis缓存和cookie进行获取

大致思路:在用户登录验证成功时将用户信息存入redis,将redis的key值存入cookie中传入前端,之后写一个拦截器拦截用户请求(也可以用AOP 我这里用的拦截器),在用户请求中获取cookie在cookie中获取redis的key值,从redis中获取用户信息

1.1实现步骤

第一步、配置redis(我这里用的集群,可用单个redis或者分片式)

//为了代码解耦将redis地址写活
//redis.properties中写法:
//redis.nodes=192.168.126.129:7000,192.168.126.129:7001,192.168.126.129:7002,192.168.126.129:7003,192.168.126.129:7004,192.168.126.129:7005
@PropertySource("classpath:properties/redis.properties")
@Configuration
public class RedisConfig {
   
    @Value("${redis.nodes}")
    private String nodes;   //node,node,node
    @Bean
    public JedisCluster jedisCluster(){
   
        String[] strNodes = nodes.split(","); //[node1,nod2,nod3.....]
        Set<HostAndPort> set = new HashSet<>();
        for(String node : strNodes){
     //node=host:port
            String host = node.split(":")[0];
            int port = Integer.parseInt(node.split(":")[1]);
            set.add(new HostAndPort(host,port));
        }
        return new JedisCluster(set);
    }
    }

第二步、写controller层 登录 储存信息

//JedisCluster 为配置的redis集群
  @Autowired
    private JedisCluster jedisCluster;
     @RequestMapping("doLogin")
    @ResponseBody
    //SysResult 为自定义结果集 需要的话最下面取
    public SysResult doLogin(User user, HttpServletResponse httpServletResponse) {
   
		//userService.doLogin中验证账号密码是否正确
        userService.doLogin(user);
        //如果程序执行到这里,说明用户名密码正确,开启流程 随机一个ticket为密钥信息
        String ticket=UUID.randomUUID().toString().replace("-", "");
        //脱敏处理 余额/密码/手机号/家庭住址 防止信息泄露
        user.setPassword("123456");
        //ObjectMapperUtil json转换工具类 需要的话最下面取
        String userJSON = ObjectMapperUtil.toJSON(user);
        //保存到redis中
        jedisCluster.setex(ticket, 7 * 24 * 60 * 60, userJSON);
        if (StringUtils.isEmpty(ticket)) {
   
        //信息检验 返回报错信息
            return SysResult.fail();
        }
        //1创建cookie对象
        Cookie cookie = new Cookie("CS_TICKET", ticket);
        //2.设置cookie存活的时间 value=-1 当用户关闭会话时,cookie删除
        //2.设置cookie存活的时间 value=-0 当用户关闭会话时,立即删除cookie
        //2.设置cookie存活的时间 value=>0 当用户关闭会话时,设定cookie超时时间、
        cookie.setMaxAge(7 * 24 * 60 * 60);
        //3.在cs.com中实现数据共享
        cookie.setDomain("cs.com");
        cookie.setPath("/");
        //将数据保存到浏览器中
        httpServletResponse.addCookie(cookie);
		//返回成功成功信息
        return SysResult.success();
    }

第三步、自定义拦截器

//拦截器的类(业务)      拦截器的配置文件(拦截什么请求)
@Component
public class UserInterceptor implements HandlerInterceptor {
   
	//登录时存储的TICKET的名字
    private static final String TICKET 
  • 1
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值