我在显示HashMap中的键和值时遇到问题,其中的值位于用户定义的类中,这是显示的错误



Student.class

class Student
{
   private String name;
   private int age;
   //getter and setter
}


我的控制器:

@RequestMapping(value = "/showStudent", method = RequestMethod.GET)
public ModelAndView retrievesession(HttpSession session)
{
    ModelAndView mav = new ModelAndView("ShowStudent");
    Map<String,ArrayList<Student>> classList = new HashMap<String,ArrayList<Student>>();
    ArrayList<Student> student = new ArrayList<Student>();

    String nameUser = (String) session.getAttribute("name");
    String trackUser = (String) session.getAttribute("track");

    if(nameUser.equals("Kakashi") && trackUser.equals("Konoha"))
    {
        student.add(new Student("Naruto",12));
        student.add(new Student("Sasuke",13));
        classList.put("Ninja", student);

        mav.addObject("classList", classList);
    }

    else if(nameUser.equals("Goku") && trackUser.equals("Earth"))
    {
        student.add(new Student("Gohan",25));
        student.add(new Student("Goten",13));
        classList.put("Fighter", student);

        mav.addObject("classList", classList);
    }

    else if(nameUser.equals("Ryuk") && trackUser.equals("Killer"))
    {
        student.add(new Student("Kira",22));
        student.add(new Student("L",21));
        classList.put("Reaper", student);

        mav.addObject("classList", classList);
    }

    return mav;
}


我的JSP:

<h3>Name: ${name}</h3>
<h3>Track: ${track}</h3><br/><br/><br/>
<h3>Your student from ${classList.key}</h3>
<c:if test="${not empty classList}">
    <table>
    <c:forEach items="${classList}" var="classList">
       <tr>
           <td>${classList.value.name}</td>
           <td>${classList.value.age}</td>
       </tr>
    </c:forEach>
    </table>
</c:if>


我不知道我是否做对了,它只是显示我遇到问题的值,还可以添加else语句,因此如果会话为null,它将返回登录名。页?

最佳答案

在地图上进行迭代,您将获得另一个需要迭代的集合,然后才能获取对象的属性。

<table>
<c:forEach items="${classList}" var="list">
  <tr><td><h3>Your student from ${list.key}</h3></td></tr>
  <tr><td>
   <table>
   <c:forEach items="${list.value}" var="student">
       <tr>
           <td>${student.name}</td>
           <td>${student.age}</td>
       </tr>
    </c:forEach>
   </table>
  </td></tr>
</c:forEach>
</table>

10-04 19:08