编写一个jsp页面,该页面提供一个表单,用户可以通过表单输入三角形的三条边,并提交给本jsp页面,该jsp页面将计算三角形的面积任务交给一个bean完成。jsp页面使用getProperty动作标记显示三角形的面积
时间: 2023-12-10 09:39:55 浏览: 69
下面是一个简单的示例,演示如何编写一个JSP页面来计算三角形的面积:
triangle-form.jsp:
```jsp
<html>
<head>
<title>Triangle Area Calculator</title>
</head>
<body>
<h1>Triangle Area Calculator</h1>
<form method="post" action="triangle-area.jsp">
<label for="sideA">Side A:</label>
<input type="number" name="sideA" id="sideA" required>
<br>
<label for="sideB">Side B:</label>
<input type="number" name="sideB" id="sideB" required>
<br>
<label for="sideC">Side C:</label>
<input type="number" name="sideC" id="sideC" required>
<br>
<input type="submit" value="Calculate">
</form>
</body>
</html>
```
triangle-area.jsp:
```jsp
<%@ page import="com.example.TriangleBean" %>
<jsp:useBean id="triangle" class="com.example.TriangleBean" scope="request"/>
<%
double sideA = Double.parseDouble(request.getParameter("sideA"));
double sideB = Double.parseDouble(request.getParameter("sideB"));
double sideC = Double.parseDouble(request.getParameter("sideC"));
triangle.setSides(sideA, sideB, sideC);
double area = triangle.getArea();
%>
<html>
<head>
<title>Triangle Area Calculator</title>
</head>
<body>
<h1>Triangle Area Calculator</h1>
<p>The area of the triangle with sides <%= triangle.getSideA() %>, <%= triangle.getSideB() %>, and <%= triangle.getSideC() %> is <%= area %> square units.</p>
</body>
</html>
```
TriangleBean.java:
```java
package com.example;
public class TriangleBean {
private double sideA;
private double sideB;
private double sideC;
public void setSides(double sideA, double sideB, double sideC) {
this.sideA = sideA;
this.sideB = sideB;
this.sideC = sideC;
}
public double getSideA() {
return sideA;
}
public double getSideB() {
return sideB;
}
public double getSideC() {
return sideC;
}
public double getArea() {
double s = (sideA + sideB + sideC) / 2;
return Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC));
}
}
```
注意,上述代码并没有进行输入验证和错误处理。在实际应用中,应该对用户输入进行验证,并在输入不合法或计算出错时给出友好的提示信息。
阅读全文