用eclipse的jsp文件做一个计算器
时间: 2024-09-24 09:25:33 浏览: 51
使用JSP制作一个超简单的网页计算器的实例分享
在Eclipse中创建一个简单的JSP计算器,你可以按照以下步骤操作:
1. **新建项目**:
- 打开Eclipse,点击`File` -> `New` -> `Dynamic Web Project`,创建一个新的动态Web项目。
2. **添加JSP页面**:
- 在项目的`WebContent` -> `Web-INF` -> `pages`目录下,右键选择`New` -> `JSP File`,命名为`calculator.jsp`。
3. **编写HTML结构**:
- 使用文本编辑器打开`calculator.jsp`,开始编写HTML结构,包括输入框、按钮以及显示结果的区域。例如:
```html
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>简单计算器</title>
</head>
<body>
<h1>简易计算器</h1>
<form action="calculate" method="post">
Number 1: <input type="number" id="num1" name="num1"><br>
Number 2: <input type="number" id="num2" name="num2"><br>
Operation: <select name="operation">
<option value="add">+</option>
<option value="subtract">-</option>
<option value="multiply">*</option>
<option value="divide">/</option>
</select><br>
<input type="submit" value="Calculate">
</form>
<p>Result: <%= result %> (如果需要计算)</p>
</body>
</html>
```
4. **处理后端逻辑**:
- 创建一个Servlet(如CalculatorServlet.java),用于接收表单提交的数据并在后台进行计算:
```java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class CalculatorServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String num1 = request.getParameter("num1");
String num2 = request.getParameter("num2");
String operation = request.getParameter("operation");
double num1Double = Double.parseDouble(num1);
double num2Double = Double.parseDouble(num2);
double result;
switch (operation) {
case "add":
result = num1Double + num2Double;
break;
case "subtract":
result = num1Double - num2Double;
break;
case "multiply":
result = num1Double * num2Double;
break;
case "divide":
if (num2Double != 0) {
result = num1Double / num2Double;
} else {
// 处理除数为零的情况
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Division by zero is not allowed.");
return;
}
break;
default:
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid operation.");
return;
}
request.setAttribute("result", result);
request.getRequestDispatcher("calculator.jsp").forward(request, response);
}
}
```
5. **部署应用**:
- 将`CalculatorServlet`保存,并配置好web.xml以关联Servlet。
6. **测试计算器**:
- 在浏览器中访问`http://localhost:8080/your-project-context/calculator.jsp`,即可看到并使用计算器。
阅读全文