创建三角形JavaBean,定义若干个三角形对象存入ArrayList,使用<c:forEach>循环遍历集合中的对象,并输出对象的属性
时间: 2024-05-12 11:13:15 浏览: 106
首先,我们需要定义一个三角形的JavaBean,包含三个属性:边长a、边长b、边长c。代码如下:
Triangle.java
```java
public class Triangle {
private double a;
private double b;
private double c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public double getA() {
return a;
}
public void setA(double a) {
this.a = a;
}
public double getB() {
return b;
}
public void setB(double b) {
this.b = b;
}
public double getC() {
return c;
}
public void setC(double c) {
this.c = c;
}
}
```
接下来,我们可以创建一个ArrayList对象,存放若干个Triangle对象。代码如下:
```java
ArrayList<Triangle> triangles = new ArrayList<>();
triangles.add(new Triangle(3, 4, 5));
triangles.add(new Triangle(5, 12, 13));
triangles.add(new Triangle(7, 24, 25));
```
最后,在JSP页面中,使用<c:forEach>循环遍历集合中的对象,并输出对象的属性。代码如下:
```jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>Triangle List</title>
</head>
<body>
<h1>Triangle List</h1>
<table border="1">
<tr>
<th>Side A</th>
<th>Side B</th>
<th>Side C</th>
</tr>
<c:forEach items="${triangles}" var="triangle">
<tr>
<td>${triangle.a}</td>
<td>${triangle.b}</td>
<td>${triangle.c}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
```
在这个例子中,我们使用了EL表达式来访问Triangle对象的属性,${triangle.a}表示访问Triangle对象的a属性。最终的输出结果如下:
```
Triangle List
Side A Side B Side C
3.0 4.0 5.0
5.0 12.0 13.0
7.0 24.0 25.0
```
阅读全文