使用Servlet+JSP实现简单的计算器功能,主要要求如下;input.jsp;两个数据的输入及运算符的选择
时间: 2024-01-21 21:17:36 浏览: 75
首先,我们需要一个输入页面(input.jsp),用于输入两个数和运算符:
```html
<!DOCTYPE html>
<html>
<head>
<title>简单计算器</title>
</head>
<body>
<h1>简单计算器</h1>
<form action="calculate" method="post">
<input type="number" name="num1" placeholder="请输入第一个数"><br><br>
<input type="number" name="num2" placeholder="请输入第二个数"><br><br>
<select name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select><br><br>
<input type="submit" value="计算">
</form>
</body>
</html>
```
接下来,我们需要一个 Servlet (CalculateServlet)来处理表单提交的数据,并进行计算:
```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 {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String num1Str = request.getParameter("num1");
String num2Str = request.getParameter("num2");
String operator = request.getParameter("operator");
if(num1Str != null && num2Str != null) {
double num1 = Double.parseDouble(num1Str);
double num2 = Double.parseDouble(num2Str);
double result = 0;
switch(operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if(num2 != 0) {
result = num1 / num2;
} else {
response.getWriter().println("除数不能为0!");
return;
}
break;
default:
response.getWriter().println("无效的运算符!");
return;
}
response.getWriter().println("计算结果为:" + result);
} else {
response.getWriter().println("请输入两个数!");
}
}
}
```
最后,我们需要在 web.xml 文件中配置 Servlet:
```xml
<web-app>
<servlet>
<servlet-name>CalculateServlet</servlet-name>
<servlet-class>CalculateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CalculateServlet</servlet-name>
<url-pattern>/calculate</url-pattern>
</servlet-mapping>
</web-app>
```
现在我们就可以在浏览器中访问 input.jsp 页面,输入两个数和运算符,点击“计算”按钮进行计算了。
阅读全文