编写封装计算矩形的周长和面积的JavaBean(Rectangle.java ),编写网页 rectangle.html 输入矩形的长和宽,如图 1 所示;编写 rectangle.jsp 调用 JavaBean 分别计算矩形的周长和面积,输出如图 2 所示。
时间: 2024-11-30 09:14:49 浏览: 23
首先,让我们分步说明如何完成这个任务:
1. 创建Rectangle.java JavaBean:
```java
// Rectangle.java
import javax.servlet.jsp.JspException;
import java.util.Map;
public class Rectangle {
private double length;
private double width;
// 构造函数
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Getter和Setter方法
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
// 计算周长和面积的方法
public double calculatePerimeter() {
return 2 * (length + width);
}
public double calculateArea() {
return length * width;
}
// JSP可以调用此方法显示结果
public String displayResults(Map<String, Double> params) throws JspException {
double perimeter = calculatePerimeter();
double area = calculateArea();
return "长:" + params.get("length") + " 宽:" + params.get("width") +
"\n周长:" + perimeter + "\n面积:" + area;
}
}
```
2. 编写HTML页面rectangle.html:
```html
<!DOCTYPE html>
<html>
<head>
<title>矩形计算器</title>
</head>
<body>
<form action="rectangle.jsp" method="post">
长:<input type="number" name="length"><br>
宽:<input type="number" name="width"><br>
<input type="submit" value="计算">
</form>
</body>
</html>
```
3. 编写JSP页面rectangle.jsp:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>矩形周长和面积</title>
</head>
<body>
<%@ include file="Rectangle.java" %>
<jsp:useBean id="rectangle" class="Rectangle" scope="request"/>
<h2>计算结果:</h2>
<c:if test="${not empty rectangle}">
${rectangle.displayResults(request.getParameterMap())}
</c:if>
</body>
</html>
```
在这个例子中,用户在rectangle.html中输入矩形的长和宽,然后提交到rectangle.jsp。JSP页面会创建Rectangle对象,获取用户输入,调用其`displayResults`方法计算并显示周长和面积。
阅读全文