Recent development projects, encountered with other team development, although the same as Java, but the infrastructure is completely different, in order to avoid conflict, we use the same Web container, the deployment of different services, sharing the mechanism of the session, to achieve the essence of prose: the form of scattered God.
First look at the Tomcat configuration, open Conf/server.xml, find the Host node, add two context nodes as follows:
<context path= "/master" docbase= "Master" reloadable= "true" crosscontext= "true" ></Context> <context Path= "/slave" docbase= "Slave" reloadable= "true" crosscontext= "true" ></Context>
Where Master is the main service, including user login, exit module, slave is a small function module, need to get login user information from session.
The key configuration is crosscontext= "true"
In Master's login filter, add the following code:
Long TM = System.currenttimemillis (); Cookie cookie = new Cookie ("__luid", Long.tostring (tm)); Cookie.setpath ("/"); Cookie.setmaxage (-1); Response.addcookie (cookie); Map<long,string> usermap = null; Try{usermap = (MAP) session.getservletcontext (). getattribute ("UserMap"); }catch (Exception e) {usermap = new Hashmap<long, string> (); Session.getservletcontext (). SetAttribute ("UserMap", USERMAP); } usermap.put (Tm,ppuser.getuserid ());
The following method is called in the slave filter:
private integer getcrossuserid (httpservletrequest request) { try{ cookie cookie = getcookie (Request, "__luid") ; if (cookie==null) return null; servletcontext context = request.getsession (). Getservletcontext (). GetContext ("/master"); if (context==null) return null; Map<Long,Integer> userMap = null; userMap = (MAP) context.getattribute ("UserMap"); if (Usermap.size () >10000) clearusermap (UserMap); long luid = long.parselong (Cookie.getValue ()); integer iuserid = usermap.get (LUID); request.setattribute (REQUEST_ Attr_userid, iuserid); return iuserid; } catch (exception e) { e.printstacktrace (); } return null; }
The principle is as follows:
The main service maintains a usermap, inserts the current login user data into the UserMap, and puts UserMap into the current servletcontext;
Reads the master service's ServletContext from the service, obtains to UserMap, obtains the user information according to the cookie data.
Form Scatter God: Tomcat under Multiple virtual directory sharing Session method