【问题标题】:ClassCastError when share objects between webapp在 webapp 之间共享对象时发生 ClassCastError
【发布时间】: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


    【解决方案1】:

    第一个 webapp 中对象的类由第一个 webapp 类加载器加载。第二个 webapp 类加载器将同名的类加载到第二个 webapp 中。因此,即使两个应用都可以访问同名的类,它们也是两个不同的类,因为它们不是由同一个类加载器加载的。

    我不会尝试以这种方式在应用程序之间共享对象。它无论如何都不会在集群环境中工作,并且更安全的容器在被要求提供另一个 servlet 上下文时可能会返回 null。考虑在两个应用程序之间共享一个数据库,并将共享数据存储在共享数据库中。

    如果您仍想走这条路,请确保共享类在容器的类路径中,而不是在每个 webapp 类路径中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-22
      • 2012-08-18
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多