1.预备知识及注意点:
2.共享技术的实现方法一
a)监听类配置
- 首先创建监听类CartSessionListen,并定义一个静态Map变量sessions用于存放在被创建的session及其对应的sessionID;
- 在web.xml中配置监听类。
public class CartSessionListen implements HttpSessionListener {
private static Map<String, HttpSession> sessions = new HashMap<String, HttpSession>();
public void sessionCreated(HttpSessionEvent sessionEvent) {
sessions.put(sessionEvent.getSession().getId(), sessionEvent.getSession());
// System.out.println("session被创建");
}
public void sessionDestroyed(HttpSessionEvent sessionEvent) {
sessions.remove(sessionEvent.getSession().getId());
// System.out.println("session被销毁");
}
public static HttpSession getSession(String sessionID) {
return sessions.get(sessionID);
}
public static void remove(String sessionid){
sessions.remove(sessionid);
}
}
<listener>
<listener-class>com.myshop.web.action.shopping.CartSessionListen</listener-class></listener>
b)Action中的逻辑处理
- 在action中,首先获取当前session,并从中获取购物车对象buyCart;
- 若无法获取buyCart,则先从cookie中获取sessionID。若存在sessionID,则从监听类CartSessionListen的静态Map变量sessions中通过该sessionID查找session。
- 若session被获取到,则从该session中获取buyCart,并从静态Map变量sessions中移除该session;(注:后面将会将获取到的buyCart加入到当前session中,而当前session在被创建时已经被加入到sessions中,下次查找的session将会是现在的当前session,而原来的session以后不会再用到,故而需将其中sessions中移除)
- 如果此时还没获取到buyCart,说明以往session中并没有创建过buyCart,所以创建新的购物车对象buyCart;
- 将buyCart加入到当前session中;
- 最后将当前sessionID加入cookie中,即加入name为字符串"sessionID"且value为当前sessionID的cookie。
BuyCart buyCart = (BuyCart)request.getSession().getAttribute("buyCart");
if(buyCart==null){
String sessionID = WebUtil.getCookieByName(request, "sessionID");
if(sessionID!=null){
HttpSession session = CartSessionListen.getSession(sessionID);
if(session!=null){
buyCart = (BuyCart)session.getAttribute("buyCart");
if(buyCart!=null)CartSessionListen.remove(sessionID);
}
}
}
if(buyCart==null){
buyCart = new BuyCart();
}
request.getSession().setAttribute("buyCart", buyCart);
WebUtil.addCookie(response, "sessionID", request.getSession().getId(),
request.getSession().getMaxInactiveInterval());
3.共享技术的实现方法二
BuyCart buyCart = (BuyCart)request.getSession().getAttribute("buyCart");
if(buyCart==null){ buyCart = new BuyCart();
request.getSession().setAttribute("buyCart", buyCart); }
WebUtil.addCookie(response, "JSESSIONID",request.getSession().getId(),
request.getSession().getMaxInactiveInterval());