当前位置: 代码迷 >> J2EE >> java.lang.ClassCastException: java.lang.String cannot be cast to common.User解决思路
  详细解决方案

java.lang.ClassCastException: java.lang.String cannot be cast to common.User解决思路

热度:494   发布时间:2016-04-22 02:34:07
java.lang.ClassCastException: java.lang.String cannot be cast to common.User
java.lang.ClassCastException: java.lang.String cannot be cast to common.User
at Server.RequestProcessor.logout(RequestProcessor.java:147)
at Server.RequestProcessor.run(RequestProcessor.java:38)
at java.lang.Thread.run(Thread.java:662)

其中User是
public class User implements Serializable {
private static final long serialVersionUID = -427838794924380991L;
private String id;
private String password;
private String box1;
private String grade;
private String department;
private String ip;

public User(String id,String password, String box1, String department,String grade,String ip) {
this.id=id;
this.password = password;
this.box1 = box1;
this.department =department;
this.grade = grade;
this.ip = ip;
}

public User(String id, String password) {
this.id = id;
this.password = password;
}

报错的地方是:
 /** 客户端退出 */
public boolean logout(OnlineClientIOCache oio, Request request) throws IOException{
System.out.println(currentClientSocket.getInetAddress().getHostAddress()+ ":" + currentClientSocket.getPort() + "走了");
User user0 = (User)request.getAttribute("user");

ServerDataBuffer.onlineUserIOCacheMap.remove(user0.getid());//把当前上线客户端的IO从Map中删除
ServerDataBuffer.onlineUsersMap.remove(user0.getid());//从在线用户缓存Map中删除当前用户

Response response = new Response(); //创建一个响应对象
response.setType(ResponseType.LOGOUT);
response.setData("logoutUser", user0);
oio.getOos().writeObject(response); //把响应对象往客户端写
oio.getOos().flush();
currentClientSocket.close(); //关闭这个客户端Socket
ServerDataBuffer.onlineUserTableModel.remove(String.valueOf(user0.getid())); //把当前下线用户从在线用户表Model中删除
return false; //断开监听
}  

这是什么原因啊?

------解决方案--------------------
探讨
User user0 = (User)request.getAttribute("user");

------解决方案--------------------
探讨

引用:
User user0 = (User)request.getAttribute("user");


你这个在set的时候是User对象么?

代码补全,给全了!

------解决方案--------------------
request中存的user不是你的User对像,是一字符串?
你在什么地方set的user,看一下
------解决方案--------------------
探讨
request中存的user不是你的User对像,是一字符串?
你在什么地方set的user,看一下

------解决方案--------------------
你写了几个User 是不是类加错了?
------解决方案--------------------
User user0 = (User)request.getAttribute("user");
其中request.getAttribute("user");得到的是字符串,如果要上面的式子合法,那可以这样,user0.setId=request.getAttribute("user");
以此类推吧。
不过,看得出你是想把一个user对象放到attribute中。不知道你是怎么set的
------解决方案--------------------
探讨
/** 关闭客户端 */
private void logout() {
int select = JOptionPane.showConfirmDialog(ChatFrame.this,"确定退出吗?\n\n退出程序将中断与服务器的连接!", "退出聊天室",JOptionPane.YES_NO_OPTION);
if (select == JOptionPane.YES_OPTION)……

------解决方案--------------------
req.setAttribute("user", ClientDataBuffer.currentUser);

其中currentUser定义为public static String currentUser; /** 当前客户端的用户信息 */

LZ这个这么明显是不能强转成User对象的呀!!!
  相关解决方案