作用:1、在项目中避免两个用户同时登录,2、在用户长时间不登陆、断网等情况下,将登录日志中的状态设置成退出
实现原理:利用session监听机制,将项目中的在线的session记录下来,存放在全局变量中,动态的加载session和销毁session
实现代码:
1、创建session监听类
public class SessionListener extends HttpServlet implements HttpSessionListener {
@SuppressWarnings("unchecked")
public static Map userMap = new HashMap();
private MySessionContext myc=MySessionContext.getInstance();
/**
* 监听session的创建
*/
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
myc.AddSession(httpSessionEvent.getSession());
}
/**
* 监听session的销毁
*/
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
try {
//也可以自定义销毁操作
ApplicationContext app= (ApplicationContext) this.getServletContext().getAttribute("org.springframework.web.context.WebApplicationContext.ROOT");
IndexAction indexAction = (IndexAction)app.getBean("IndexAction");
indexAction.loginLog();
myc.DelSession(httpSessionEvent.getSession());
} catch (Exception e) {
}
}
}
2、session存放类
/**
* 这是一个全局类,设置成单例模式,相当于全局变量
*/
public class MySessionContext {
private static MySessionContext instance;//创建一个私有地静态对象
@SuppressWarnings("unchecked")
private HashMap mymap;//创建一个sessionMAP
@SuppressWarnings("unchecked")
private MySessionContext() {//设置一个私有的构造方法
mymap = new HashMap();
}
/**
* 创建一个静态生成对象实例的方法
* 该方法只有在第一次调用时实例一个对象
*/
public static MySessionContext getInstance() {
if (instance == null) {
instance = new MySessionContext();
}
return instance;
}
/**
* 创建一个线程同步的函数,向mymap中添加session对象
* @param session
*/
@SuppressWarnings("unchecked")
public synchronized void AddSession(HttpSession session) {
if (session != null) {
mymap.put(session.getId(), session);
}
}
/**
* 创建一个线程同步的函数,从mymap中删除session对象
* @param session
*/
public synchronized void DelSession(HttpSession session) {
if(session!=null){
try {
//session.removeAttribute("userkey");
//销毁session
session.invalidate();
mymap.remove(session.getId());
} catch (Exception e) {
}
}
}
/**
* 创建一个线程同步的函数,从mymap中根据sessionId返回session对象
* @param session
*/
public synchronized HttpSession getSession(String session_id) {
if (session_id == null) return null;
return (HttpSession) mymap.get(session_id);
}
}
3、在web.xml中设置监听
<!-- session 超时设定 -->
<session-config>
<session-timeout>90</session-timeout>
</session-config>
<!-- session 监听设置 -->
<listener>
<listener-class>
com.geo.rbac.common.mysession.SessionListener
</listener-class>
</listener>
浙公网安备 33010602011771号