在同一服务器中跨 Web 应用程序共享 servlet 上下文 [英] sharing servlet context across web applications in same server

查看:35
本文介绍了在同一服务器中跨 Web 应用程序共享 servlet 上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在同一个容器 (Tomcat) 中运行的单独 Web 应用程序中有两个 servlet.让应用程序成为 app1 &app2, &servlet 是 serv1 &服务 2.

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.

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

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>

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

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.

推荐答案

目前看起来还不错.显然它已被其他地方维护/生成的 context.xml 覆盖.您可以阅读 Tomcat 的 Context关于规则的配置参考.例如,您在 webapp 的 /META-INF 中有一个吗?然后你应该在那里定义 crossContext .

It looks fine so far. Apparently it's been overridden by a context.xml maintained/generated elsewhere. You can read in the Tomcat's Context configuration reference about the rules. Do you for example have one in webapp's /META-INF? You should then define crossContext in there.

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

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:

这篇关于在同一服务器中跨 Web 应用程序共享 servlet 上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆