restful接口通过sessionId获取指定session

目前并没有方法直接通过sessionId找到指定的session.
我们需要在session创建时,手动的将该session和它的sessionId以值和键的方式存放到一个Map中,这样就可以根据sessionId从map中找到对应的session.
实现:首先创建一个session的监听事件
MySessionListener.java:

public class MySessionListener implements HttpSessionListener {
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    MySessionContext.AddSession(httpSessionEvent.getSession());
    }

    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        MySessionContext.DelSession(session);
    }

}

web.xml添加一个监听器:

<listener>
<listener-class>listener.MySessionListener</listener-class>
</listener>

全局静态map

MySessionContext.Java:

public class MySessionContext {
    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);
    }
}

使用:通过sessionId从map中取值
String sessionId = request.getParameter("sessionId");

HttpSession session = MySessionContext.getSession(sessionId);

猜你喜欢

转载自siyunx.iteye.com/blog/2336064
今日推荐