0

In short:In my JSP, I need to iterate over a list of custom defined bean class, like List,MyClass has key and value variables, and also getters and setters for the same, using the c:foreach jstl

Details: something like this:

<c:forEach var="myObject" items="${model.pair_list}">
                    <li data-value="${myObject.key}">${myObject.value}</li>
                </c:forEach>

In the Java code, I have :

List pairlist = new ArrayList(); //MyClass is a simple bean class with variables "key", and "value", and getters and setters for the same //put a few values in this list model.put("pair_list", pairlist);

Any hints how to get this working?

Saurabh J
  • 113
  • 8

3 Answers3

1

At first in Java create a List of MyClass and populate it

    List<MyClass> pairList = new ArrayList<>();

    //assuming key and value are of type String 
    //repeat the following 4 lines as much as needed
    MyClass myClass = new MyClass();
    myClass.setKey("...");
    myClass.setValue("...");
    pairList.add(myClass); 

    //Create an Map as you model and add pairList to it
    Map<String, List<MyClass>> model = new HashMap<>();
    model.put('pair_list', pairList);

    //Now you can add it to request for passing it to JSP/JSTL
    request.setAttribute('model', model);  

Then in JSTL it is quite the same as you mentioned in your question

    <c:forEach var="myObject" items="${model.pair_list}">
        <li data-value="${myObject.key}">${myObject.value}</li>
    </c:forEach>
Ashraf Purno
  • 1,055
  • 6
  • 11
1

Consider your items attribute
Can you remove . pairList ?

Example, when you pass data from controller to view in Java code

List<YourObjectClass> YourArrayListData = new ArrayList<YourObjectClass>();
..........................
.... ADD DATA PROCESS ....
..........................
request.setAttribute("YourArrayList", YourArrayListData);

this is the jstl code on jsp file

<c:forEach items="${YourArrayList}" var="referenceIt" >
${referenceIt.property}
</c:forEach>
ZenithS
  • 824
  • 6
  • 17
  • This is what I did, but didnt work. Let me try again and I will get back with the issues I get while debugging – Saurabh J Nov 09 '15 at 14:41
  • There was a condition in my Java code which was stopping this from getting executed: model.put('pair_list', pairList); – Saurabh J Nov 10 '15 at 10:16
1

In your servlet just put the list on the request that you send to Jsp

On request

request.setAttribute("pair_list", pairlist);

Note: Use forward not sendRedirect

In your JSP :-

<c:forEach var="myObject" items="${pair_list}">
    <li data-value="${myObject.key}">${myObject.value}</li>
</c:forEach>
Community
  • 1
  • 1
karim mohsen
  • 2,051
  • 1
  • 11
  • 18