Hawk
Hawk

Reputation: 13

Spring Mvc display data from multiple Lists in Jsp

Hi there I am using Spring MVC and I am trying to display some data from multiple Lists in a jsp page. I've searched and found some similar topics but I wasn't able to achieve what I am trying to do plus got more confused. My model class contains something like this:

private String BlaBla1;

private String BlaBla2;

private List<String> Alpha;

private List<String> Beta; 
.....
//getters setters

What I want is to display a table in a jsp with the values from these two Lists (Alpha and Beta ..) one value at a column.They both have the same number of values. For Example

<tr><td>Alpha.value1</td><td>Beta.value1</td></tr>
<tr><td>Alpha.value2</td><td>Beta.value2</td></tr>
......................................
<tr><td>Alpha.valueN</td><td>Beta.valueN</td></tr>

As I've seen here rendering data in jsp using spring controllers and different classes

and some other examples, they create something like that: List<MyObjects> objects but MyObjects model always has private String ... and NOT any List<String>..

I tried to construct something like that

Map<String,List<String>> test = new HashMap<String,List<String>>();

then

test.put("alfa", Alpha);
test.put("beta", Beta);

but all I got was just display them in 2 rows and a single column using

<c:forEach var="testValue" items="${test}">
    <tr><td>${testValue.value}</td></tr>
</c:forEach>

Please don't aske me to change my Model class, it is 'impossible'. I've seen somewhere saying to use Collection but I'm not sure how to do that.

Any suggestion would be useful, happy coding!

Upvotes: 1

Views: 2724

Answers (2)

Nikhil
Nikhil

Reputation: 310

model.addObject("alphaList", alpha);
model.addObject("betaList", beta);

In the jsp :

<c:forEach var="listItem" items="${alphaList}" varStatus="theCount" >
    <tr><td>${listItem}</td><td>${betaList[theCount.index]}</td></tr>
</c:forEach>

Note : ${theCount.index} starts with 0 ${theCount.count} starts with 1.

So basically you can use the count to iterate over the second list.

Upvotes: 2

Serge Ballesta
Serge Ballesta

Reputation: 148880

You just have to iterate the Alpha list normally ... but with use of the varStatus attribute of <c:foreach > tag. This varStatus has (among others) an attribute index which is the index of the iteration and all what you need to display corresponding element from Beta list. Code example :

<c:forEach var="alphaVal" items="${Alpha}" varStatus="status">
    <tr><td>${alphaVal}</td><td>${Beta[status.index]}</td></tr>
</c:forEach>

Upvotes: 1

Related Questions