0
votes

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?

3

3 Answers

1
votes

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>
1
votes

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>
1
votes

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>