思路:
1.在登录的controller层中先判断用户是否登录成功,如果登录成功,每次都用session去获取sessionid,并且把它保存到application作用域中,同时还要把当前用户的登录信息也保存作用域和session里面
2.创建一个自定义拦截器SysInterceptor,使用每次请求登录都去拦截对比登录信息,如果第一次登录的用户和第二次登录的用户两个的登录信息一致并且sessionid不一致,则移除前一个用户的session,并给出提示页面,让其重新登录,否则正常的走流程登录
具体实现代码:
Controller层登录代码
if(null != user){//登录成功
String sessionId = session.getId(); //每次登录的时候获取用户的sessionid
request.getServletContext().setAttribute("sessionid", sessionId); //把当前用户登录的sessionid存到application作用域中
request.getServletContext().setAttribute("Devuser", user);
/* System.err.println("打印sessionid身份令牌:>>>>>>>>>>>>>>>>>>>>>"+sessionId);*/
//放入session
session.setAttribute(Constants.DEV_USER_SESSION, user);
//页面跳转(main.jsp)
return "redirect:/dev/flatform/main";
}else{
//页面跳转(login.jsp)带出提示信息--转发
request.setAttribute("error", "用户名或密码不正确");
return "devlogin";
}
自定义拦截器SysInterceptor
public class SysInterceptor extends HandlerInterceptorAdapter {
private Logger logger = Logger.getLogger(SysInterceptor.class);
public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception{
HttpSession session = request.getSession(); //获取session
String applicationSessionid = (String) request.getServletContext().getAttribute("sessionid"); //登录的sessionid
DevUser applicationDevUser = (DevUser) request.getServletContext().getAttribute("Devuser"); //登录的用户
String sessionId = request.getSession().getId(); //获取当前登录的sessionid
BackendUser backendUser = (BackendUser)session.getAttribute(Constants.USER_SESSION);
DevUser devUser = (DevUser)session.getAttribute(Constants.DEV_USER_SESSION);
//判断如果用户存在,并且sessionid不一致,让前一个session失效
if((devUser!=null) && (devUser.getDevCode().equals(applicationDevUser.getDevCode())) && (!applicationSessionid.equals(sessionId))){
session.removeAttribute(Constants.DEV_USER_SESSION);
response.sendRedirect(request.getContextPath()+"/401.jsp");
return false;
}
if(null != devUser){
return true;
}else if(null != backendUser){
return true;
}else{
response.sendRedirect(request.getContextPath()+"/403.jsp");
return false;
}
}
}
springMVC.xml拦截器部分配置
<!-- 配置interceptors -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/manager/backend/**"/>
<mvc:mapping path="/dev/flatform/**"/>
<bean class="cn.appsys.interceptor.SysInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
实现效果如下:
用户A登录:
用户B登录:
当用户A登录后,用户B再登录,用户A再刷新页面则跳到提示页面