【发布时间】:2013-03-15 06:44:25
【问题描述】:
注意:这不是交叉发布(尽管它与我的另一个问题 shared objects between webapps of the same tomcat 有关)
我有 2 个 web 应用程序在两个上下文中运行:c1、c2(都紧跟在根目录之后)。我在 c1 中放了一个 startupListener 来共享一个变量,在 c2 中放另一个来检索它。问题是如果我共享一个内置数据类型的对象(如 HashMap、Integer、...),那没问题,但不能转换自定义数据类型。例如,如果我有一个名为 User 的自定义类,并传递该类型的对象,则会发生 ClassCastError。
我在 c1 中的启动监听器是:
public void contextInitialized(ServletContextEvent sce) {
User user = new user("name");
Integer exampleInt = 1;
ServletContext context = sce.getServletContext().getContext("/c1");
if (context!=null)
{
context.setAttribute("user", user);
context.setAttribute("id", exampleInt);
}
}
在c2 app中是这样的:
public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext().getContext("/c1");
Integer integer = (Integer) context.getAttribute("id");//this line is OK
Object object = context.getAttribute("user");
User userObject = (User) object; //this line triggered error
User user = (User) context.getAttribute("user");// also trigger error
}
为什么会这样? (一个班级抱怨自己铸造?)。任何解决方法:我想在同一个 jvm 的上下文之间共享我的对象。 谢了。
【问题讨论】:
标签: java web-applications servlets