java 对session的简单管理

session的监听器:

package com.dtgy.youguoju.Listener;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.dtgy.youguoju.utils.SessionUtils;

public class AllSessionListener implements HttpSessionListener {
    /**
     * session创建
     */
    @Override
    public void sessionCreated(HttpSessionEvent arg0) {
        
    }
    /**
     * session失效
     */
    @Override
    public void sessionDestroyed(HttpSessionEvent arg0) {
        //获取session
         HttpSession session = arg0.getSession();
         //删除
        SessionUtils.DelSession(session);
    }

}

管理类:

package com.dtgy.youguoju.utils;

import java.util.HashMap;

import javax.servlet.http.HttpSession;

public class SessionUtils {
     private static HashMap mymap = new HashMap();
     /**
      * 添加session
      * @param session  要添加的session
      */
        public static synchronized void AddSession(HttpSession session) {
            if (session != null) {
                mymap.put(session.getId(), session);
            }
        }
        /**
         * 删除session(在session监听器中监听失效时就删除)
         * @param session   要删除的session
         */
        public static synchronized boolean DelSession(HttpSession session) {
            if (session != null) {
                mymap.remove(session.getId());
                return true;
            }
            return false;
        }
        /**
         * 删除session
         * @param sessionId 要删除的sessionId
         * @return 
         */
        public static synchronized boolean DelSession(String sessionId) {
            if (sessionId == null)
            return true;
            mymap.remove(sessionId);
            return true;
        }
        /**
         * 获取session
         * @param sessionId     sessionId
         * @return
         */
        public static synchronized HttpSession getSession(String sessionId) {
            if (sessionId == null)
            return null;
            return (HttpSession) mymap.get(sessionId);
        }
        /**
         * 获取session的key值
         * @param session       session
         * @return
         */
        public static synchronized Object getSessionKeyVal(HttpSession session,String key){
            if (session==null)
                return null;            
            return session.getAttribute(key);
        }
        /**
         * 获取session的key值
         * @param sessionId     sessionId
         * @return
         */
        public static synchronized Object getSessionKeyVal(String sessionId,String key){
            if (sessionId == null)
            return null;
            HttpSession httpSession = mymap.get(sessionId);
            if (httpSession==null)
                return null;            
            return httpSession.getAttribute(key);
        }               
}

你可能感兴趣的:(java 对session的简单管理)