gpt4 book ai didi

java - 在同一服务器中跨 Web 应用程序共享 servlet 上下文

转载 作者:行者123 更新时间:2023-11-28 22:07:02 26 4
gpt4 key购买 nike

我有两个 servlet,每个 servlet 都在同一个容器 (Tomcat) 中运行的单独 Web 应用程序中。让应用程序为 app1 和 app2,而 servlet 为 serv1 和 serv2。

我正在使用 serv1(在 app1 中)调用 serv2(在 app2 中)。我还试图在这两个 servlet 之间共享同一个 session 。下面是我的代码片段。

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");

服务器.xml

<Host>
<Context path="/app1" crossContext="true" />
<Context path="/app2" crossContext="true" />
</Host>

问题是我在 serv2 getAttribute() 中遇到空指针异常。根本原因是 getContext("/app1") 返回 null。上下文名称是正确的。我不知道为什么我无法检索 servlet 上下文。我不想使用 cookie 或 url 重写。请帮忙。

最佳答案

到目前为止看起来还不错。显然它已被在别处维护/生成的 context.xml 覆盖。您可以在 Tomcat 的 Context configuration reference 中阅读关于规则。例如,您是否在 webapp 的 /META-INF 中有一个?然后,您应该在其中定义 crossContext

或者您是否使用像 Eclipse 这样的 IDE 来部署网络应用程序或其他东西?然后必须将 IDE 配置为不部署到工作区元数据中,而是直接部署到 Tomcat 中,否则 Eclipse 将使用它自己的 context.xml 副本(您可以在 Servers 项目)。您可以在服务器的首选项中配置它。这是来自 Eclipse 的屏幕:

enter image description here

关于java - 在同一服务器中跨 Web 应用程序共享 servlet 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7891817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com