原来
原来我们使用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;
}
}
老铁如果对你对你有帮助的话