I have a table that is populated depending on how many cars are there. If the number of cars is 1 it will give me the 1 row (where 5 attributes are arranged in 5 columns). If开发者_运维百科 the number of cars is 2 it will give me 2 rows(same 5 attributes), & so on. Now I need to split the table into as many cars are there so that there is just one row for every car. I need to do it in JSP and trying to use the tag <c:choose>
or <c:if>
, but isn't working . Please help
You need <c:forEach>
here. With it you can iterate over any List<T>
and print the <tr>
on every iteration. Assuming that you have populated a List<Car>
and put it in the EL scope as ${cars}
, here's an example:
<table>
<c:forEach items="${cars}" var="car">
<tr>
<td>${car.make}</td>
<td>${car.model}</td>
<td>${car.type}</td>
<td>${car.color}</td>
<td>${car.price}</td>
</tr>
</c:forEach>
</table>
See also:
- Beginning and intermediate JSP/Servlet tutorials
- Hidden features of JSP/Servlet
<html>
<head>
<title>Sample code - Traversing an HTML Table with JavaScript and DOM Interfaces</title>
<script>
function start() {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// creating all cells
for (var j = 0; j < 2; j++) {
// creates a table row
var row = document.createElement("tr");
for (var i = 0; i < 2; i++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode("cell is row "+j+", column "+i);
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
</script>
</head>
<body onload="start()">
</body>
</html>
精彩评论