日期:2014-05-19  浏览次数:20612 次

大神,请进。诡异的类型转换异常。
各位大牛,来看看看这个异常吧。

代码背景:
这是两个项目的整合,在A项目中用session set了一个对象,然后将其封装到一个servletContext中,代码如下:
Java code
HttpSession session = request.getSession(true);
        session.setAttribute(Constant.USER_SESSION, user);
        ServletContext context=session.getServletContext();
        context.setAttribute("session", session);


然后在B项目中获取这个user对象,代码如下:
Java code
HttpSession session=request.getSession();
        ServletContext Context=session.getServletContext();
        ServletContext Context1=Context.getContext("/A");
        if(Context1 !=null && !Context1.equals("")){    
            HttpSession sess =(HttpSession)Context1.getAttribute("session");
            User user=(User)sess.getAttribute(Constant.USER_SESSION);
            if(user!=null)
                System.out.println("username:--------"+user.getUserName());
        }

然后抛出一个类型转换异常:
Java code
java.lang.ClassCastException: com.nodoor.vo.User cannot be cast to com.nodoor.vo.User

我这样测试了下:System.out.println(sess.getAttribute(Constant.USER_SESSION) instanceof User)
结果竟然是false....求解。。。。
诡异的异常。纠结我一天了。。求解脱。


------解决方案--------------------
不是一个user
------解决方案--------------------
User在另外一个项目中使用时,包名 也必须跟session中存的那个 User一样,否则也会被认为两个User是不同的对象。
------解决方案--------------------
不同的ServletContext的实例也是不同的....建议楼主将传对象改为传基本类型数组,过来再封装对象。