实现多个浏览器窗口可共享购物车的技术

1、创建Session监听器

package com.zyx.web.action.shopping;


import java.util.HashMap;

import java.util.Map;


import javax.servlet.http.HttpSession;

import javax.servlet.http.HttpSessionEvent;

import javax.servlet.http.HttpSessionListener;


public class SiteSessionListener implements HttpSessionListener {


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

public void sessionCreated(HttpSessionEvent sessionEvent) {

System.out.println(sessionEvent.getSession().getId());

sessions.put(sessionEvent.getSession().getId(), sessionEvent.getSession());

}


public void sessionDestroyed(HttpSessionEvent sessionEvent) {

sessions.remove(sessionEvent.getSession().getId());

}


public static HttpSession getSession(String sessionId){

return sessions.get(sessionId);

}

}


2、web.xml中配置listener

<!-- session创建与关闭监听,取得sessionid -->

<listener>

     <listener-class>com.zyx.web.action.shopping.SiteSessionListener</listener-class>

</listener>


3、Action中获取原有的sessionid

package com.zyx.web.action.shopping;


import java.util.Date;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;


import org.apache.struts.action.Action;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

import org.springframework.stereotype.Controller;


@Controller("/shopping/cart")

public class CartAction extends Action {


@Override

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws Exception {

String sid = request.getParameter("sid");

HttpSession session = SiteSessionListener.getSession(sid);

if(session == null){

request.getSession().setAttribute("buycart", new Date());

}else{

request.setAttribute("message", session.getAttribute("buycart"));

}

return mapping.findForward("cart");

}

}


4、页面测试

<%@ page language="java" pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

 <head>

   <title>购物车</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">    

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

 </head>


 <body>

   ${message }<br>

 </body>

</html>