例如用户在A浏览器上登陆了,然后用手机打开B浏览器又登陆了,要让A浏览器上的用户退出(用户再次操作时提示登陆即可)
我的设计如下,这样设计有什么问题吗?因为有时候会报错
java.lang.IllegalStateException: getAttribute: Session already invalidated
我的代码:
//登陆方法
private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//验证用户通过
....
//判断当前用户是否已经登陆,如果已经登陆,清掉之前的登陆信息(上次登陆失效);
if(isAlreadyLogin(user.getId(),request)){
Map<String,HttpSession> sessionMap = (Map<String, HttpSession>)request.getServletContext().getAttribute("sessionMap");
try {
sessionMap.get(user.getId()).removeAttribute("userID");**//这句报错**
sessionMap.get(user.getId()).removeAttribute("user");
} catch (Exception e) {
// TODO Java.lang.IllegalStateException: getAttribute: Session already invalidated
}
}
//登陆成功 ,设置session
request.getSession(true).setAttribute("user", user);
request.getSession(true).setAttribute("userID", user.getId());
addSessionToMap(user.getId(), request);
....
}
//退出方法
private void logOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
String userId = (String)request.getSession().getAttribute("userID");
removeSessionToMap(userId,request);
request.getSession().removeAttribute("userID");
request.getSession().removeAttribute("user");
//返回信息
......
}
/**
* 判断用户是否已经登录
*/
private static boolean isAlreadyLogin(String userId,HttpServletRequest request){
ServletContext application = request.getServletContext();
Map<String,HttpSession> sessionMap = (Map<String,HttpSession>)application.getAttribute("sessionMap");
if(sessionMap==null||sessionMap.get(userId)==null){
return false;
}
return true;
}
请大牛指教,谢了。
繁星点点滴滴
米琪卡哇伊
森栏
相关分类