要实现一个简易的四则运算Web页面,可以使用JSP和Servlet进行开发。以下是实现步骤及代码示例:
### 步骤:
1. **创建JSP页面**用于输入数字和选择运算符。
2. **创建Servlet**处理运算逻辑和异常情况。
### 示例代码:
#### 1. index.jsp(输入页面)
<!DOCTYPE html>
<html>
<head>
<title>四则运算</title>
</head>
<body>
<h1>简易四则运算</h1>
<form action="CalculatorServlet" method="post">
<input type="text" name="num1" placeholder="输入第一个数字" required>
<select name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" name="num2" placeholder="输入第二个数字" required>
<input type="submit" value="计算">
</form>
<p>${message}</p>
</body>
</html>
#### 2. CalculatorServlet.java(Servlet处理逻辑)
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/CalculatorServlet")
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 operator = request.getParameter("operator");
String message = "";
try {
double number1 = Double.parseDouble(num1);
double number2 = Double.parseDouble(num2);
double result = 0;
switch (operator) {
case "+":
result = number1 + number2;
break;
case "-":
result = number1 - number2;
break;
case "*":
result = number1 * number2;
break;
case "/":
if (number2 == 0) {
throw new ArithmeticException("除数不能为零");
}
result = number1 / number2;
break;
}
message = "结果: " + result;
} catch (NumberFormatException e) {
message = "请输入有效的数字";
} catch (ArithmeticException e) {
message = e.getMessage();
}
request.setAttribute("message", message);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
### 注意事项:
- 确保你的项目中有正确配置的`web.xml`或使用注解。
- 确保JSP页面中有引用`message`来输出结果或提示。
- 捕获非数字输入异常,并给予用户友好的提示。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |