Search code examples
javajsparrayliststruts2ognl

Mapping a list with JSP page and getting values in Action class. It gives the result list as a cartesian product in Action class


I am working on a project where I have to send data from JSP page to action class in the form of List, I am setting List<Object> from action class first time when it mapped with JSP page, when I am doing action for saving the details, In action I get a values of List<Object> like as Cartesian Product for each value.

e.g. If there are List of 3 Objects(having 4 member fields) passing to JSP, when returning to action it generates 12 objects with different values of JSP.

The Image shows the Demo UI, it is not a table, but each Row represents an object of list

The image shows the Demo UI which I need
In The action class

 List<Pojo> PojoList = new ArrayList<Pojo>();

Can anyone suggest me what approach should I use, this is new scenario for me, I also tried some example from internet but not succeed, I also iterate the list in JSP but It was giving me an error.(not exactly error but it does not give fields on JSP);

In JSP:

<c:forEach var="pojo" items="${pojoList}">
    <s:textarea name="pojo.field1">
    <s:textarea name="pojo.field2">
    <s:textarea name="pojo.field3">
    <s:textarea name="pojo.field4">
</c:forEach>

Return In Action Class method(It prints 12 objects)

try {
    System.out.println("List : "+pojoList);
    for (Iterator<Pojo> iterator = pojoList.iterator(); iterator.hasNext();) {
        Pojo pojo = (Pojo) iterator.next();
        System.out.println("\n MB : "+pojo);
       }
} catch (Exception e) {
    e.printStackTrace();
}

Please suggest me whats going wrong.


Solution

  • If you have 3 pojos in the list then each one have 4 fields added to the list by default, so 3*4 = 12. The code is working fine, but if you change it like

    <s:iterator value="pojoList" status="stat">
        <s:textarea name="pojoList[%{#stat.index}].field1">
        <s:textarea name="pojoList[%{#stat.index}].field2">
        <s:textarea name="pojoList[%{#stat.index}].field3">
        <s:textarea name="pojoList[%{#stat.index}].field4">
    </s:iterator>
    

    it will use the same index for each field, so 3 pojos will be created/updated.