如何将对象从控制器传递到jsp页面,然后迭代对象以在表中显示它们?


问题内容

我正在从事Spring MVC项目,在该项目中,我需要将对象从Controller传递到JSP,然后需要迭代该对象并将其显示在jsp页面的表中。

下面是我的类,其中包含数据-

public class DatacenterMachineMapping {

    private String datacenter;
    private List<MachineMetrics> metrics;

    // getters and setters
}

public class MachineMetrics {

    private String machineName;
    private String t2_95;
    private String t2_99;
    private String syncs;
    private String syncsBehind;
    private String average;

    // getters and setters
}

下面是我在Controller中的方法,我需要从该方法将一个对象传递给JSP,然后在JSP中迭代该对象以在表中显示数据-

@RequestMapping(value = "testOperation", method = RequestMethod.GET)
public Map<String, String> testData() {

    final Map<String, String> model = new LinkedHashMap<String, String>();

    MachineMetrics metrics1 = new MachineMetrics();
    metrics1.setAvg("10");
    metrics1.setT2_95("100");
    metrics1.setT2_99("200");
    metrics1.setMachineName("machineA");
    metrics1.setSyncs("100");
    metrics1.setSyncsBehind("1000");

    MachineMetrics metrics2 = new MachineMetrics();
    metrics2.setAvg("20");
    metrics2.setT2_95("200");
    metrics2.setT2_99("300");
    metrics2.setMachineName("machineB");
    metrics2.setSyncs("200");
    metrics2.setSyncsBehind("2000");

    List<MachineMetrics> metrics = new LinkedList<MachineMetrics>();
    metrics.add(metrics1);
    metrics.add(metrics2);

    DatacenterMachineMapping mappings = new DatacenterMachineMapping();
    mappings.setColo("dc1");
    mappings.setMetrics(metrics);

    return model;   
}

下面是我的JSP页面。我不确定如何mappings在JSP页面中以上述方式使用上述对象,以便我可以对其进行迭代并在表中显示结果-

<body>
    <table>
        <thead>
            <tr>
                <th>Machine Name</th>
                <th>T2_95</th>
                <th>T2_99</th>
                <th>Syncs</th>
                <th>Syncs Behind</th>
                <th>Average</th>
            </tr>
        </thead>
        <tbody>

            <!-- what to do here? -->

        </tbody>
    </table>
</body>

我的数据在表中应如下所示Datacenter 1-

Machine Name    T2_95   T2_99   Syncs   Syncs Behind    Average

machineA        100     200     100     1000            10
machineB        200     300     200     2000            20

我需要为此使用JSTL吗?还是有更好的方法呢?


问题答案:

使用以下命令将JSTL库导入到您的JSP页面中

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

这会将JSTL名称空间链接到c。JSTL将使forEach标记可用,该标记可用于遍历您的集合。

确保您的对象遵循Bean命名约定

<c:forEach items="${dc1.metrics}" var="m">
    <tr>
        <td>${m.machineName}</td>
        <td>${m.t2_95}</td>
        <td>${m.t2_99}</td>
        <td>${m.syncs}</td>
        <td>${m.syncsBehind}</td>
        <td>${m.average}</td>
    </tr>
</c:forEach>