【发布时间】:2011-12-15 01:31:15
【问题描述】:
我在同一个容器 (Tomcat) 中运行的单独 Web 应用程序中有两个 servlet。让应用程序是 app1 和 app2,而 servlet 是 serv1 和 serv2。
我正在使用 serv1(在 app1 中)调用 serv2(在 app2 中)。我还尝试在这两个 servlet 之间共享同一个会话。下面是我的代码片段。
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>
问题是我在 serv2 getAttribute() 中得到空指针异常。根本原因是,getContext("/app1") 正在返回 null。上下文名称是正确的。我不知道为什么我无法检索 servlet 上下文。我不想使用 cookie 或 url 重写。请帮忙。
【问题讨论】:
-
那个
<Host>不应该进入web.xml。既然这会导致 XML 解析错误,我敢打赌你只是打错了“web.xml”?还是您真的在web.xml文件中有它,IDE 和/或 servletcontainer 的 XML 解析器是否过于宽容? -
对不起。它不是 web.xml。它的 server.xml