给出简单代码实现
时间: 2024-02-28 13:51:58 浏览: 74
求简易的代码
好的,以下是一个简单的实现示例:
JSP 页面:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>矩形计算器</title>
</head>
<body>
<h1>矩形计算器</h1>
<form action="RectangleServlet" method="post">
<label for="length">长度:</label>
<input type="text" id="length" name="length"><br>
<label for="width">宽度:</label>
<input type="text" id="width" name="width"><br>
<button type="submit">计算</button>
</form>
<% if (request.getAttribute("result") != null) { %>
<p>面积:${result.area},周长:${result.perimeter}</p>
<% } %>
</body>
</html>
```
Servlet:
```
@WebServlet("/RectangleServlet")
public class RectangleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RectangleServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取用户输入
double length = Double.parseDouble(request.getParameter("length"));
double width = Double.parseDouble(request.getParameter("width"));
// 创建矩形对象并计算面积和周长
Rectangle rectangle = new Rectangle(length, width);
double area = rectangle.getArea();
double perimeter = rectangle.getPerimeter();
// 将计算结果存储在请求属性中
request.setAttribute("result", new RectangleResult(area, perimeter));
// 转发请求到 JSP 页面
request.getRequestDispatcher("rectangle.jsp").forward(request, response);
}
}
```
JavaBean:
```
public class Rectangle {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getLength() {
return length;
}
public double getWidth() {
return width;
}
public double getArea() {
return length * width;
}
public double getPerimeter() {
return 2 * (length + width);
}
}
```
结果对象:
```
public class RectangleResult {
private double area;
private double perimeter;
public RectangleResult(double area, double perimeter) {
this.area = area;
this.perimeter = perimeter;
}
public double getArea() {
return area;
}
public double getPerimeter() {
return perimeter;
}
}
```
需要注意的是,这只是一个简单的实现示例,你需要根据具体需求进行修改和调整。同时,为了更好的代码可读性和维护性,你可以采用 MVC 模式来组织你的代码。
阅读全文