1.Java通过sessionid获取session对象


之前在实现uploadify文件上传时,遇到火狐浏览器不兼容的问题,在网上找了些资料,自己动手把他解决了,其中有一个就是session的重新发起。特此记录。

因为Servlet2.1之后不支持SessionContext里面getSession(String id)方法。

所以我们可以通过HttpSessionListener监听器和全局静态map自己实现一个SessionContext。

 1 public class MySessionContext {
 2     private static HashMap mymap = new HashMap();
 3     public static synchronized void AddSession(HttpSession session) {
 4         if (session != null) {
 5             mymap.put(session.getId(), session);
 6         }
 7     }
 8     public static synchronized void DelSession(HttpSession session) {
 9         if (session != null) {
10             mymap.remove(session.getId());
11         }
12     }
13     public static synchronized HttpSession getSession(String session_id) {
14         if (session_id == null)
15         return null;
16         return (HttpSession) mymap.get(session_id);
17     }
18 }

监听器: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>

接下来你就可以在Action中根据sessionId获取Session对象了:

String sessionId = request.getParameter("sessionId");传递的sessionid
HttpSession session = MySessionContext.getSession(sessionId);

 在火狐浏览器uploadify文件上传就会用到这个东西,当然这是我个人的处理方式,可能还有更牛逼的方法;

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM