jsp+servlet实现计算器
时间: 2023-09-13 17:05:59 浏览: 146
以下是一个简单的 JSP + Servlet 实现计算器的示例:
首先,在 JSP 页面中创建一个表单,让用户输入两个数字和选择要执行的操作:
```html
<!DOCTYPE html>
<html>
<head>
<title>计算器</title>
</head>
<body>
<form action="CalculatorServlet" method="post">
<label>第一个数字:</label>
<input type="number" name="num1"><br>
<label>第二个数字:</label>
<input type="number" name="num2"><br>
<label>操作:</label>
<select name="operator">
<option value="add">加</option>
<option value="subtract">减</option>
<option value="multiply">乘</option>
<option value="divide">除</option>
</select><br>
<input type="submit" value="计算">
</form>
</body>
</html>
```
然后,创建一个 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 CalculatorServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取用户输入的数字和操作
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
String operator = request.getParameter("operator");
// 根据用户选择的操作执行相应的计算
int result = 0;
switch (operator) {
case "add":
result = num1 + num2;
break;
case "subtract":
result = num1 - num2;
break;
case "multiply":
result = num1 * num2;
break;
case "divide":
result = num1 / num2;
break;
}
// 将计算结果返回给用户
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("<h1>结果:" + result + "</h1>");
}
}
```
最后,在 web.xml 文件中配置 Servlet 映射:
```xml
<servlet>
<servlet-name>CalculatorServlet</servlet-name>
<servlet-class>CalculatorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CalculatorServlet</servlet-name>
<url-pattern>/CalculatorServlet</url-pattern>
</servlet-mapping>
```
这样,用户就可以在浏览器中访问 JSP 页面,输入数字和选择操作,然后提交表单,得到计算结果。
阅读全文