关于使用Shiro后怎么得到用户信息

文章目录

原来

      原来我们使用Session时,是将realuser存入Session传到前台页面,但是在我们整合了Shiro后我们怎么通过Session拿到登陆用户的信息呢?

 @RequestMapping("dologin")
    public String doLogin(HttpServletRequest request, HttpServletResponse response, Userinfo user) {
        System.out.println(user + "前台得到的登录信息");
       
        //根据数据库查到的真实用户信息
        Userinfo realuser = service.login(user);
        if (realuser != null) {
            //将得到的真实用户信息存入Session
            request.getSession().setAttribute("loginuser", realuser);
            return "redirect:/index";
        } else {
            try {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().print("<script>alert('登录失败');history.go(-1);</script>");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

现在

      可以直接通过subject直接拿到登录对象,使用你登录时的对象(doGetAuthenticationInfo里面使用的登录对象)来接收就可以了

Subject subject = SecurityUtils.getSubject();
Userinfo userinfo = (Userinfo) subject.getPrincipal();
System.out.println(userinfo + "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
 /*执行认证逻辑*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证逻辑");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //编写判断逻辑
        Userinfo user = service.findByName(token.getUsername());//根据前端传来的参数到数据库查询
        if (user == null) {
            //用户名不存在
            return null;//shiro抛出UnKnowAccountException
        }
        //判断密码
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), "");
        return simpleAuthenticationInfo;
    }
}

在这里插入图片描述

老铁如果对你对你有帮助的话

在这里插入图片描述

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值