问题描述如下:
在某页面使用request时,经常会遇到空指针异常的问题,大概的问题就是例如:RoomInfo room =(RoomInfo) request.getAttribute("room");然而此时的request.getAttribute("room")为空,即room对应的request不存在,则会有空指针异常,因为我们知道,request得到的是Object对象,所以使用request的getAttribute()方法后需要进行强制转换,因为得到的结果为空,所以是不能强制转换的,那么,空指针异常就来了。
现在我有如下的一种解决方法:
RoomInfo room = null;
Object obj=null;
obj=request.getAttribute("room");
if(obj!=null){
room=(RoomInfo)obj;
}else{
room=new RoomInfo("","","","","");
}
这样就可以解决这个问题呢。