封装计算矩形周长和面积的 JavaBean(Rectangle.java),编写 rectangle.html 输入矩形长 和宽编写 rectangle.jsp 调用 JavaBean 分别计算矩形的周长和面积
时间: 2024-02-22 10:00:01 浏览: 149
好的,下面是封装计算矩形周长和面积的 JavaBean(Rectangle.java)的代码:
```java
public class Rectangle {
private double length;
private double width;
public Rectangle() {}
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 getArea() {
return length * width;
}
public double getPerimeter() {
return 2 * (length + width);
}
}
```
接下来是编写 rectangle.html 的代码,用于输入矩形的长和宽:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>矩形计算器</title>
</head>
<body>
<form action="rectangle.jsp" method="post">
<label for="length">矩形长:</label>
<input type="text" name="length"><br>
<label for="width">矩形宽:</label>
<input type="text" name="width"><br>
<input type="submit" value="计算">
</form>
</body>
</html>
```
最后是 rectangle.jsp 的代码,用于调用 JavaBean 计算矩形的周长和面积:
```jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>矩形计算器</title>
</head>
<body>
<%-- 获取输入的矩形长和宽 --%>
<%
String lengthStr = request.getParameter("length");
String widthStr = request.getParameter("width");
double length = Double.parseDouble(lengthStr);
double width = Double.parseDouble(widthStr);
%>
<%
Rectangle rect = new Rectangle();
rect.setLength(length);
rect.setWidth(width);
double area = rect.getArea();
double perimeter = rect.getPerimeter();
%>
<%-- 输出计算结果 --%>
<p>矩形面积为:<%= area %></p>
<p>矩形周长为:<%= perimeter %></p>
</body>
</html>
```
注意:在实际应用中,需要进行参数校验和异常处理。这里只是简单地演示了如何使用 JavaBean 计算矩形的周长和面积。
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)