2009年3月22日星期日

WLS_060:不同的Web应用之间如何共享Session?

开发环境:WebLogic Server 12c开发版。
WebLogic Server支持同一个ear中不同的Web应用共享Session,详见《同一个ear中不同的Web应用如何共享Session?》,但是如果是不在一个ear中Web应用如何共享Session呢?
回答是把session对象放到ServletContext中。

值得注意的是这种用法不可移植,这是WebLogic自己的特性,不是规范中的。
因为根据规范,使用ServletContext.getContext("/appA")时,应用服务器可以出于安全的原因而返回null。

重点步骤说明:

1. shoppingcart1.war
(1)修改shoppingCart.java,在service方法后面增加

// put session into shoppingcart1's ServletContext      
        ServletContext context = getServletConfig().getServletContext();
        context.setAttribute("shoppingCartApp1", session);
说明:获取到ServletContext 对象后,把整个session对象放到ServletContext 中。

(2)修改viewShoppingCart.java,在service方法后面增加

// get session from shoppingcart2's ServletContext
ServletContext context =  getServletConfig().getServletContext();
ServletContext context2 = context.getContext("/shoppingcart2");
if (context2 != null) {
HttpSession session2 = (HttpSession)context2.getAttribute("shoppingCartApp2");
System.out.println("############### get session from shoppingcart2's ServletContext: " + session2);
     
if (session2 != null){
    Vector scitems1 = (Vector) session2.getAttribute("cart");
   if (scitems1 == null)
   {
    System.out.println("Nothing in shopping cart");
   } else {
     Enumeration enum = scitems1.elements();
     System.out.println("Your shopping cart includes: ");
       while (enum.hasMoreElements())
       {
             shoppingCartItem item = (shoppingCartItem) enum.nextElement();
             System.out.println("\tItem: " + item.getName() + " price: " + item.getPrice());
}
   }
}
}
}
说明:获取到/shoppingcart2的context后,再获取shoppingcart2应用的session对象,并循环遍历。

2. shoppingcart2.war
仿照shoppingcart1.war做相应修改。

3. shoppingcart.jar
把shoppingcart1.war 和shoppingcart2.war 中保存在session中的对象shoppingCartItem单独拿出来。
打成jar,放到[domain_name]\lib目录下。

4. 运行效果
(1)访问http://localhost:7001/shoppingcart1/,购买一些商品。
(2)访问http://localhost:7001/shoppingcart2/,查看购买的商品,发现看到了在shoppingcart1/购买的商品。说明shoppingcart2访问到了shoppingcart1的session对象。

Project 下载:shoppingcart(ServletContextSessionShare).7z

参考文献:
1. http://blog.csdn.net/yousuf007/article/details/5252604
2. http://johnchina.blog.51cto.com/4390273/922071
3. http://www.cnblogs.com/lcuzhanglei/archive/2012/06/11/2545240.html
4. http://energykey.iteye.com/blog/701721
5. http://panyongzheng.iteye.com/blog/1263411
6. http://java8988.iteye.com/blog/1174959

没有评论: