---
title: "在同一个tomcat下，不同的web项目共享session "
author: "cy913417"
date: "2013-05-06T17:35:07Z"
tags: []
categories: ["企业架构"]
slug: "tomcat-web-session"
draft: false
lastmod: "2013-05-06T17:35:31Z"
id: 1860619
url: "https://it456.iteye.com/blog/1860619"
---

有时我们会遇到一个大点的项目，为了方便实现有些功能，我们会把项目拆成不同的独立web项目。

但我们在管理这些项目时，只有一个登陆口，然后在其他项目取session来实现身份的验证。

1、配置tomcat下 conf/server.xml文件，在&lt;Host&gt;&lt;/Hoser&gt;配置如下：

       &lt;Host name="localhost"  appBase="webapps"  
            unpackWARs="true" autoDeploy="true"  
            xmlValidation="false" xmlNamespaceAware="false"&gt;

    &lt;!-- aa 和bb 为两个不同的web项目  --&gt;

     &lt;Context path="/aa"  reloadable="true" crossContext="true" /&gt;  
    &lt;Context path="/bb"  reloadable="true" crossContext="true"/&gt;

      &lt;/Host&gt;

2、 在 aa项目存入session

     session.setAttribute("user",new Date().toString()+"weiqingli");  
    ServletContext ContextA =session.getServletContext();  
    ContextA.setAttribute("session", session);

3、在bb 项目取出 session

    HttpSession session1 =request.getSession();    
       ServletContext Context = session1.getServletContext();    
       ServletContext Context1= Context.getContext("/aa");      
        if(Context1 !=null && !Context1.equals("")){        
            HttpSession sess =(HttpSession)Context1.getAttribute("session");  
            out.println(sess.getAttribute("user"));  
        }

 

大家可能很容易看得出这个是单向传的session，其实要实现双向，将上面的程序反写就可以实现从bb存入，aa取出了。

本文来自CSDN博客，转载请标明出处：http://blog.csdn.net/weiqingli190949353/archive/2011/06/22/6562312.aspx