I have two servlets each in a separate web app running in the same container (Tomcat). Let the apps be app1 & app2, & servlets be serv1 & serv2.
I’m using serv1 (in app1) to call serv2(in app2).Im also trying to share a same session across these two servlets. Below is my code fragment.
serv1 (app1):
URLConnection connection = new URL("http://localhost:8080/app2/serv2").openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
HttpSession session = request.getSession(true);
String sessionId = session.getId();
ServletContext myContext = getServletContext();
myContext.setAttribute("MYSHAREDSESSIONID", sessionId);
myContext.setAttribute("SHAREDSESSION", session);
serv2( app2):
ServletContext callingContext = getServletContext().getContext("/app1");
String jsessionId = (String)callingContext .getAttribute("MYSHAREDSESSIONID");
server.xml
<Host>
<Context path="/app1" crossContext="true" />
<Context path="/app2" crossContext="true" />
</Host>
The problem is Im getting null pointer exception in serv2 getAttribute(). The root cause is, the getContext("/app1") is returning null. The context names are correct. I don’t know why Im not able to retrieve the servlet context. I don’t want to use cookies or url rewriting. Please help.
It looks fine so far. Apparently it’s been overridden by a
context.xmlmaintained/generated elsewhere. You can read in the Tomcat’sContextconfiguration reference about the rules. Do you for example have one in webapp’s/META-INF? You should then definecrossContextin there.Or are you using an IDE like Eclipse to deploy the webapps or something? The IDE has then to be configured to not deploy into workspace metadata, but straight into Tomcat, otherwise Eclipse will use its own copy of
context.xml(which you can find in Servers project). You can configure it in the server’s preferences. Here’s a screen from Eclipse: