---
title: "在同一个tomcat下，不同的web项目共享session"
author: "duchq044"
date: "2011-11-01T11:46:07Z"
tags: ["Java", "Tomcat", "session"]
categories: ["企业架构"]
slug: "tomcat-web-session"
draft: false
lastmod: "2011-11-01T11:46:07Z"
id: 1226585
url: "https://duchq044.iteye.com/blog/1226585"
---

有时我们会遇到一个大点的项目，为了方便实现有些功能，我们会把项目拆成不同的独立web项目。 但我们在管理这些项目时，只有一个登陆口，然后在其他项目取session来实现身份的验证。 1、配置tomcat下 conf/server.xml文件，在配置如下： 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取出了。