当我尝试转换session.getAttribute时,我得到了一个classcast异常?

时间:2014-12-18 21:19:46

标签: java jsp

当我尝试将session.getAttribute转换为一个lessonselection bean时,我得到一个classcast异常,这是我的工作:

bean类:

public class LessonSelection implements Serializable{

private HashMap<String, Lesson> chosenLessons = new HashMap<String, Lesson>();
private int ownerID;
private DataSource ds = null;
private ResultSet rs = null;
private PreparedStatement st = null;
//private String LessonID;
//int counter for number of max lessons willl need to be 10.

public LessonSelection() {
}

public Set getItems() {
    return chosenLessons.entrySet();
}

控制器代码:

  if (action.equals("/lessonTimetable")) {
        if (request.getParameter("btnSelect") != null) {
            this.selectedLesson = session.getAttribute("lessons") == null ? new LessonSelection(getID) : (LessonSelection) session.getAttribute("lessons");
            lessons.ID = request.getParameter("lessonID");
            lessons.description = request.getParameter("lessonDescription");
            lessons.date = request.getParameter("lessonStartDate");
            lessons.startTime = request.getParameter("lessonStartTime");
            lessons.endTime = request.getParameter("lessonEndTime");
            lessons.level = Integer.parseInt(request.getParameter("lessonLevel"));
            System.out.println(lessons + "" + selectedLesson);
            this.selectedLesson.addLesson(lessons);
            session.setAttribute("lessons", this.selectedLesson.getItems());
            //check for duplicate lessons
            rd = this.getServletContext().getRequestDispatcher("/LessonSelectionView.jspx");

查看:

<c:forEach var="getAll" items="${lessons}">
                    <tr>
                        <td>
                            <c:out value="${getAll.value.description}"/>
                        </td>
                        <td>
                            <c:out value="${getAll.value.date}"/>
                        </td>
                        <td>
                            <c:out value="${getAll.value.startTime}"/>
                        </td>
                        <td>
                            <c:out value="${getAll.value.endTime}"/>
                        </td>
                        <td>
                            <c:out value="${getAll.value.level}"/>
                        </td>

只有当我尝试将第二课添加到所选列表时才会出现此异常,它会添加第一个但我在检索先前创建的会话时遇到问题。

java.lang.ClassCastException: java.util.HashMap$EntrySet cannot be cast to model.LessonSelection

,请帮助我,我将非常感谢

1 个答案:

答案 0 :(得分:0)

您获得的错误仅表示此行错误:

this.selectedLesson = session.getAttribute("lessons") == null ? new LessonSelection(getID) : (LessonSelection) session.getAttribute("lessons");

您正在尝试将session.getAttribute("lessons") java.util.HashMap$EntrySet投射到LessonSelection。您只需要查看代码的这一部分,即session.getAttribute("lessons")的实际类型以及您尝试将其转换为错误类型的原因。您可能需要更改代码中某些元素的类型。