Search code examples
spring-mvcspring-bootjstljsp-tags

getting value in JSP by using field name


I have requirement something similar like below in our application,

I would like to show the below details in the form of table.

Country   Name  Population  CapitalCity    Aria
US        XX    XX          XX              XX
IN        YY    YY          YY              YY

User can choose in the configuration page which columns he is interested to see.

In the backend I set model attributes as below(using spring MVC),

model.addAttribute("selColumns", "column keys");
model.addAttribute("countryDetails", "List  of country details");

In the CountryDetail class, field names and selColumns key names are same.

class CountryDetails {

  private String country,
                 population,
                 CapitalCity,
                 Aria;
 }

In the UI I am trying with the following code to achieve the same.

<table class="table table-hover table-bordered table-striped">
        <thead>
            <tr>
                <c:forEach items="${selColumns}" var="item">
                <th><spring:message code="${item}" /></th>
                </c:forEach>
            </tr>
        </thead>

        <tbody>
            <c:forEach items="${countryDetails}" var="det">
                <tr>                    
                <c:forEach items="${selColumns}" var="item">
                    <td>
                    //Below code is not working
                    <c:out value="${item.det}" /></td>                  
                        </c:forEach>            
                </tr>
            </c:forEach>
        </tbody> 
    </table>

Table header is working fine. But I am struggling to show row information only for the configured columns. Code wouldn't work because it tries to find getDet() at the java side.

Could some one please help is there any way in JSP, if I give property(field) name the corresponding value would return?

Something like this

Thanks in advance, kitty


Solution

  • Try this one.

    <tbody>
            <c:forEach items="${countryDetails}" var="det">
              <tr>
                 <c:forEach items="${selColumns}" var="item">
                    <td>
                       <c:out value="${det[item]}" />
                    </td>
                 </c:forEach>
              </tr>
          </c:forEach>
    </tbody>
    

    Note:

    selColumns = ["Country", "Population", "CapitalCity", "Aria"]
    CountryDetails properties = Country,Population,CapitalCity,Aria