一、在启动类中添加全局session变量
1 @SpringBootApplication 2 public class BtkbringomgApplication { 4 public static void main(String[] args) { 5 SpringApplication.run(BtkbringomgApplication.class, args); 6 } 7 /* 全局session变量 */ 8 public static ManageSession manageSession; 9 }
二、在ShiroController中注入
1 @Autowired 2 private ManageSession manageSession;
三、在ShiroController中的登录方法下添加
@RequestMapping("/dologin")
public void login(@RequestBody User user,HttpServletRequest request){
//获取subject Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(user.username, user.password); //开始认证 subject.login(token); /** *每个账号只能在线一个 * *当前登录后其他的踢掉 **/ HttpSession httpSession = manageSession.getManageSession().get(user.getUsername()); //System.out.println("session:"+httpSession); //if (httpSession!=null && !httpSession.isNew()){ if (httpSession!=null){ //第一种方法:session销毁 httpSession.invalidate(); // 第二种方法:清除session---账户已经登录时另一个此账号直接登不进去,不建议使用 //Enumeration<String> enumeration = request.getSession().getAttributeNames(); //while (enumeration.hasMoreElements()) { //String key = enumeration.nextElement().toString(); //request.getSession().removeAttribute(key); //} } //写入session信息
manageSession.getManageSession().put(user.getUsername(),request.getSession());
}
四、有时候登录时session已经销毁导致我们销毁时出现异常信息:IllegalStateException:Session already invalidated,而shiro认证失败会走异常,会造成即使认证成功也会进异常而导致认证失败的假象,所以我们使用try/catch将其包裹对此异常进行放行。
........ catch (Exception e){ e.printStackTrace(); String messagename = e.getMessage();// 扒出异常内容 if(messagename.contains("Session already invalidated")){ //session已经销毁,放行 result.setSuccess(true); result.setMessage("认证成功"); }else{ e.printStackTrace(); //认证失败 result.setSuccess(false); result.setMessage("认证失败!"); }