3

我可以使用户的所有会话过期吗?
我知道我可以session使用session.invalidate().

我正在使用 Tomcat、servlet/JSP。

在会话中,我有一个属性userId

在此基础上,我们定义这session属于特定用户。

我需要使包含特定 userId 的所有会话无效。

4

3 回答 3

6

使用此代码管理您的活动会话并通过其 Id 获取会话,然后您可以调用此会话并在需要时使其无效:

 public class SessionListener implements HttpSessionListener  
{  

     private static Map<String, HttpSession> map = new   
                                     HashMap<String, HttpSession>();  

    public void sessionCreated(HttpSessionEvent event)  
    {  
        String id = event.getSession().getId();  
        logger.debug("session created : " + id);  
        // STORE THE SESSOIN FOR EXAMPLE IN DATABASE 
        map.put(id, event.getSession());  
    }  

    public static HttpSession getHttpSession(String sessionID)  
    {  
        return sessionObjectMap.get(sessionID);  
    }  

    public void sessionDestroyed(HttpSessionEvent event)  
    {  
        // get the destroying session...               
    }  
} 
于 2013-05-14T07:37:36.703 回答
1

make a listner by implementing HttpSessionListener and add each created session to a data structure. . like Map or list

for Map use SessionId as Key and session object as value. . . .

Override both sessionCreated(HttpSessionEvent event) and sessionDestroyed(HttpSessionEvent event)

sessionCreated(HttpSessionEvent event) method is called when any session is created by container. . and we can do what ever we want to do with it at this creation time. . like add in list or map

sessionDestroyed(HttpSessionEvent event) is called when ever a session is destroyed or invalidated(either by code or timed out by server). . we can do what ever with it before destroy. . . like total logged time. . remove from list or map. . etc

于 2013-05-15T05:04:36.810 回答
0

您可以将所有会话值设为空..

session.removeAttribute("userId");
于 2013-05-14T07:51:56.497 回答