使用j2ee实现网页四则运算
时间: 2024-05-16 15:18:03 浏览: 86
以下是一个简单的使用 JSP 和 Servlet 实现网页四则运算的示例:
1. 首先创建一个名为 "index.jsp" 的 JSP 文件,用于显示网页表单和接收用户输入:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>网页四则运算</title>
</head>
<body>
<h1>网页四则运算</h1>
<form method="post" action="calculate">
<label for="num1">第一个数:</label>
<input type="text" name="num1" id="num1"><br><br>
<label for="num2">第二个数:</label>
<input type="text" name="num2" id="num2"><br><br>
<label for="operator">运算符:</label>
<select name="operator" id="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select><br><br>
<input type="submit" value="计算">
</form>
</body>
</html>
```
2. 创建一个名为 "CalculateServlet.java" 的 Servlet 文件,用于接收表单数据并进行运算:
```java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CalculateServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 从表单中获取数据
String num1 = request.getParameter("num1");
String num2 = request.getParameter("num2");
String operator = request.getParameter("operator");
// 将字符串转换为数字
double n1 = Double.parseDouble(num1);
double n2 = Double.parseDouble(num2);
// 根据运算符进行运算
double result = 0;
switch (operator) {
case "+":
result = n1 + n2;
break;
case "-":
result = n1 - n2;
break;
case "*":
result = n1 * n2;
break;
case "/":
result = n1 / n2;
break;
default:
break;
}
// 将结果存入 request 中
request.setAttribute("result", result);
// 跳转到结果页面
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
```
3. 创建一个名为 "result.jsp" 的 JSP 文件,用于显示计算结果:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>计算结果</title>
</head>
<body>
<h1>计算结果</h1>
<p>计算结果为:<%= request.getAttribute("result") %></p>
</body>
</html>
```
4. 部署并启动项目,访问 "index.jsp" 页面即可进行四则运算。
阅读全文