Dil*_*B S 1 java tomcat servlets
我在同一个容器 (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);
Run Code Online (Sandbox Code Playgroud)
serv2(app2):
ServletContext callingContext = getServletContext().getContext("/app1");
String jsessionId = (String)callingContext .getAttribute("MYSHAREDSESSIONID");
Run Code Online (Sandbox Code Playgroud)
服务器.xml
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);
Run Code Online (Sandbox Code Playgroud)
问题是我在 serv2 中遇到空指针异常getAttribute()。根本原因是,getContext("/app1")正在返回null。上下文名称是正确的。我不知道为什么我无法检索 servlet 上下文。我不想使用 cookie 或 url 重写。请帮忙。
到目前为止看起来还不错。显然它已被context.xml其他地方维护/生成的覆盖。您可以在 Tomcat 的Context配置参考中阅读有关规则的信息。例如,您在 webapp 中有一个/META-INF吗?然后你应该crossContext在那里定义。
或者您是否使用 Eclipse 之类的 IDE 来部署 webapps 或其他什么?然后必须将 IDE 配置为不部署到工作区元数据,而是直接部署到 Tomcat,否则 Eclipse 将使用它自己的副本context.xml(您可以在Servers项目中找到)。您可以在服务器的首选项中对其进行配置。这是来自 Eclipse 的屏幕:

| 归档时间: |
|
| 查看次数: |
6279 次 |
| 最近记录: |