编写一个文件名为TriangleServlet.java的Servlet,其URL为/computeTriangleArea.do,响应来自input.html的请求。如果能够构成三角形,则将计算得到的面积构成字符串“三角形面积=XXX”并在页面输出,要求面积保留2位小数,否则输出“三条边长无法构成三角形”,如果输入的边长为非数字型或不是正数,则在页面输出“输入的边长有误!”。
时间: 2023-05-11 21:02:18 浏览: 109
以下是TriangleServlet.java的代码:
```java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TriangleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String side1 = request.getParameter("side1");
String side2 = request.getParameter("side2");
String side3 = request.getParameter("side3");
try {
double a = Double.parseDouble(side1);
double b = Double.parseDouble(side2);
double c = Double.parseDouble(side3);
if (a <= 0 || b <= 0 || c <= 0) {
out.println("输入的边长有误!");
} else if (a + b > c && a + c > b && b + c > a) {
double p = (a + b + c) / 2;
double area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
out.printf("三角形面积=%.2f", area);
} else {
out.println("三条边长无法构成三角形");
}
} catch (NumberFormatException e) {
out.println("输入的边长有误!");
}
out.close();
}
}
```
在input.html中,可以使用以下代码来发送请求:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Triangle Area</title>
</head>
<body>
<form action="/computeTriangleArea.do" method="post">
<label>边长1:</label><input type="text" name="side1"><br>
<label>边长2:</label><input type="text" name="side2"><br>
<label>边长3:</label><input type="text" name="side3"><br>
<input type="submit" value="计算">
</form>
</body>
</html>
```
当用户输入三个边长并点击“计算”按钮时,TriangleServlet会接收到请求并进行处理,最终在页面上输出结果。
阅读全文