使用自定义Session监听器实现自定义Session管理
在学习新知识的过程中,偶然间搜到Session居然也是可以实现自定义监听的。那么监听到了Session各种状态,我们能来做些什么呢?哈哈,想必聪明的你早就想到一二三了。
实现Session自定义监听后,我们可以实现的事情:
1、监控用户的上下线操作,即使在他关闭浏览器退出的时候,也是可以的哟,哈哈
2、实现Session登记后,可以完成单用户单点登录
3、当某些账号出现异常操作后,我们可以将其强制退出,避免造成更大的损失
等等……
在此就不讲上述的功能怎么实现了。
下面,直接上代码,咱们只看重点就OK了。
1、Session监听器
package com.letsgt.sessionmanager;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.apache.log4j.Logger;
public class GTSession implements HttpSessionListener,HttpSessionAttributeListener{
private Logger log=Logger.getLogger(GTSession.class);
public void attributeAdded(HttpSessionBindingEvent event) {
HttpSession session=event.getSession();
log.debug("---->>sessionID--"+session.getId()+"---addAttribute:"+event.getName()+"----paramValue:"+event.getValue());
GTSessionContent.AddSession(session);
}
public void attributeRemoved(HttpSessionBindingEvent event) {
HttpSession session=event.getSession();
log.debug("---->>sessionID--"+session.getId()+"---removeAttribute:"+event.getName());
}
public void attributeReplaced(HttpSessionBindingEvent event) {
HttpSession session=event.getSession();
log.debug("---->>sessionID--"+session.getId()+"---repalceAttribute:"+event.getName()+"----paramValue:"+event.getValue());
}
public void sessionCreated(HttpSessionEvent event) {
HttpSession session=event.getSession();
log.debug("---->>sessionID--"+session.getId()+"-----Create-----");
GTSessionContent.AddSession(session);
}
public void sessionDestroyed(HttpSessionEvent event) {
HttpSession session=event.getSession();
log.debug("---->>sessionID--"+session.getId()+"-----Destory-----");
GTSessionContent.DelSession(session);
}
}
注意。监听器必须在web.xml中声明后才能使用的哟。
2、自定义Session上下文管理
package com.letsgt.sessionmanager;
import java.util.HashMap;
import javax.servlet.http.HttpSession;
import com.letsgt.config.Global;
import com.letsgt.domain.UserInfo;
public class GTSessionContent {
private static HashMap mymap = new HashMap();
public static synchronized void AddSession(HttpSession session) {
if (session != null) {
mymap.put(session.getId(), session);
}
}
public static synchronized void DelSession(HttpSession session) {
if (session != null) {
mymap.remove(session.getId());
}
}
public static synchronized HttpSession getSession(String session_id) {
if (session_id == null)
return null;
return (HttpSession) mymap.get(session_id);
}
}

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇:没有了
