2014-11-22 63 views
1

我有問題顯示我的鍵和值從我的HashMap其中值是用戶定義的類這裏是錯誤顯示如何使用JSTL將ModelAndView中的Hashmap的鍵和值(在UserDefinedClass中)循環到JSP使用JSTL

enter image description here

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它將返回到登錄頁面?

+0

我該怎麼做? – user14 2014-11-22 09:50:45

+0

請參閱下面的答案。 – 2014-11-22 10:17:41

回答

1

遍歷地圖,你會得到一個更收集你需要在另一個循環迭代,然後才能獲得對象的屬性。

<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> 
0

使用代碼: -

<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="class"> 
    <tr> 
     <td>${class.name}</td> 
     <td>${class.age}</td> 
    </tr> 
</c:forEach> 
</table> 

+0

嘗試過,這是新的錯誤org.apache.jasper.JasperException:javax.el.E​​LException:無法解析表達式[$ {class.name}] – user14 2014-11-22 06:27:36

相關問題