当上传图片时出现 HTTP ERROR 302 错误, 这是服务端需要登录验证,而客户端uploadify 并没有把 cookie 中的 sessionId 发送给服务器 ,如果有拦截或过滤的话,请求就会被重置,这样就会出现302错误了。
网上有一种解决方法就是在请求后面加上 sessionId (http://fanshuyao.iteye.com/blog/1751684),但好像也不怎么行。现在通过实现HttpSessionListener的sessionCreated和sessionDestroyed 能很好解决问题。
步骤如下:
1、建立自己的SessionContext
/**
* session管理,解决uploadify session丢失问题
* @author lqy
* @date 2013-1-29
*/
public class MySessionContext {
private static MySessionContext instance;
private HashMap<String, HttpSession> mymap;
private MySessionContext() {
mymap = new HashMap<String, HttpSession>();
}
public static MySessionContext getInstance() {
if (instance == null) {
instance = new MySessionContext();
}
return instance;
}
public synchronized void addSession(HttpSession session) {
if (session != null) {
mymap.put(session.getId(), session);
}
}
public synchronized void delSession(HttpSession session) {
if (session != null) {
mymap.remove(session.getId());
}
}
public synchronized HttpSession getSession(String session_id) {
if (session_id == null)
return null;
return (HttpSession) mymap.get(session_id);
}
}
2、新增一个Session监听类
/**
* Session监听器
* @author lqy
* @date 2013-1-29
*/
public class SessionListener implements HttpSessionListener {
public static Map<String,HttpSession> userMap = new HashMap<String,HttpSession>();
private MySessionContext myc = MySessionContext.getInstance();
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
myc.addSession(httpSessionEvent.getSession());
}
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
HttpSession session = httpSessionEvent.getSession();
myc.delSession(session);
}
}
3、在Web.xml中配置监听
<listener>
<listener-class>com.huaxi.expert.web.listener.SessionListener</listener-class>
</listener>
4、在程序中使用
String sid = req.getParameter("sid");
if (sid == null || sid.trim().equals("")) {
res.sendRedirect(req.getContextPath() + "/");
} else {
MySessionContext myc = MySessionContext.getInstance();
HttpSession mySession = myc.getSession(sid);
if(mySession == null){
res.sendRedirect(req.getContextPath() + "/");
}else{
chain.doFilter(request, response);
}
}
获取session
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
蕃薯耀 2013年1月29日 11:17:19 星期二