创建三角形JavaBean,定义若干个三角形对象存入ArrayList,使用<c:forEach>循环遍历集合中的对象,并输出对象的属性
时间: 2024-05-13 19:19:38 浏览: 110
首先,我们需要创建一个三角形类Triangle,包含三个成员变量表示三角形的三条边长:
```java
public class Triangle {
private double side1;
private double side2;
private double side3;
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
// getter and setter methods for the three sides
public double getSide1() {
return side1;
}
public void setSide1(double side1) {
this.side1 = side1;
}
public double getSide2() {
return side2;
}
public void setSide2(double side2) {
this.side2 = side2;
}
public double getSide3() {
return side3;
}
public void setSide3(double side3) {
this.side3 = side3;
}
}
```
然后,我们可以在Servlet中定义若干个Triangle对象,并将它们存入ArrayList中:
```java
List<Triangle> triangles = new ArrayList<>();
triangles.add(new Triangle(3, 4, 5));
triangles.add(new Triangle(5, 12, 13));
triangles.add(new Triangle(8, 15, 17));
```
最后,在JSP页面中使用<c:forEach>循环遍历ArrayList中的对象,并输出它们的属性:
```jsp
<table>
<thead>
<tr>
<th>Side 1</th>
<th>Side 2</th>
<th>Side 3</th>
</tr>
</thead>
<tbody>
<c:forEach items="${triangles}" var="triangle">
<tr>
<td>${triangle.side1}</td>
<td>${triangle.side2}</td>
<td>${triangle.side3}</td>
</tr>
</c:forEach>
</tbody>
</table>
```
这样,就可以遍历ArrayList中的Triangle对象,并输出它们的属性了。
阅读全文