How to display values of type 'UserDefinedClass' into jsp from HashMap<String, UserDefinedClass> using JSTL?

StackOverflow https://stackoverflow.com/questions/22631554

Question

Here's is the simplified version of my problem, framework is Spring MVC 3.1 and the view is JSP.

Simple POJO Class:

class User {
String userId ;
String userName;
String age;
 // getters and setters of the above.
}

Controller class:

@Controller
@SessionAttributes(value = {"userObj", "userMap"})
class UserController {
HashMap<String, User> userMap = new HashMap<String, User>();

User demoUser = new User();
demoUser.setUserId("1");
demoUser.setUserName("myname");
demoUser.setAge("45");

userMap.put(demoUser.getUserId, demoUser);

session.setAttribute("userObj", demoUser);
session.setAttribute("userMap", userMap);


//adding this objects to a ModelMap object named 'model'
model.addAttribute("userMap", userMap);
model.addAttribute("userObj", demoUser);


return "viewName" ; // name resolved to a jsp page.
}

In JSP :

<form:form method="POST" commandName="userMap" name="statusForm">   


<table class="border1">   
  <tr> 
        <th width=5px>USER ID</th>      
        <th width=15px>USER <br>Name</th>
        <th width=5px>USER AGE</th>

  </tr>

    <c:forEach var="entry" items="${userMap}" varStatus="status">

    <tr>

        <td> ${entry.key} </td>   <!--  key alone will get displayed if I comment the 'entry.values' iteration forEach loop-->

            <c:forEach var="innerLoop" items ="${entry.value}" varStatus="valuestatus">   

                <td>${innerLoop}</td>       

            </c:forEach>

    </tr>

    </c:forEach>

</table> 

</form:form>

While reaching the inner forEach loop I get a servlet error saying " Don't know how to iterate over supplied items in forEach". If I comment the second forEach loop, the map displays the keys alone. I've tried many combinations, nothing seems to be working to display the values inside the HashMap. Please advise. Thanks!

Was it helpful?

Solution

That is expexcted behaviour.You can't iterate over User referenece as this is not collection like List,Set,Map

There is no need of inner loop. You can use below code

<c:forEach var="entry" items="${userMap}" varStatus="status">

    <tr>

        <td> ${entry.key} </td>   <!--  key alone will get displayed if I comment the 'entry.values' iteration forEach loop-->
          <td> ${entry.value.userId} </td>
          <td> ${entry.value.userName} </td>
          <td> ${entry.value.age} </td>              

    </tr>

    </c:forEach>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top