ClassCastError when share objects between webapp

萝らか妹 提交于 2020-01-17 07:05:08

问题


Note: this is not cross-posting (although it's related to my other question shared objects between webapps of the same tomcat)

I have 2 webapps running at two contexts: c1, c2 (both immediately after the root). I put a startupListener in c1 to share a variable, and another one in c2 to retrieve it. The problem is if I share an object of built-in datatypes (like HashMap, Integer,...) it is ok, but custom datatype can't be cast. For example, if I have a custom class named User, and pass an object of that type around, ClassCastError happened.

My startuplistener in c1 is:

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

            }

    }

In c2 app, it is like this:

      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


      }

Why so? (a class complain about casting to itself?). Any workaround: I want to share my objects between contexts of the same jvm. Tks.


回答1:


The class of the object in the first webapp is loaded by the first webapp classloader. A class with the same name is loaded in the second webapp, by the second webapp classloader. So, even if both apps have access to a class with the same name, they're two different classes, because they're not loaded by the same classloader.

I wouldn't try to share objects between apps this way. It won't work in a clustered environment anyway, and a more secure container could return null when asked for another servlet context. Consider sharing a database between the two applications, and storing the shared data in the shared database.

If you still want to go this route, then make sure the shared classes are in the container's classpath, and not in each webapp classpath.



来源:https://stackoverflow.com/questions/15426335/classcasterror-when-share-objects-between-webapp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!