使用Servlet+JSP实现简单的计算器功能,主要要求如下;input.jsp;两个数据的输入及运算符的选择,Calculator.java;根据选择的运算符计算两个数的运算结果,并将结果转发到最终页面Result.jsp使用RequestDispatcher对象实现转发,Result.jsp显示最终结果
时间: 2024-01-21 18:17:46 浏览: 94
使用JSP+Servlet制作的简易计算器
1. 首先,我们需要创建一个名为input.jsp的JSP页面,用于输入两个数和运算符:
```
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
</head>
<body>
<h2>Calculator</h2>
<form action="Calculator" method="post">
<label for="num1">Number 1:</label>
<input type="text" id="num1" name="num1"><br><br>
<label for="num2">Number 2:</label>
<input type="text" id="num2" name="num2"><br><br>
<label for="operator">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="Calculate">
</form>
</body>
</html>
```
2. 接下来,我们需要创建一个名为Calculator.java的Servlet,用于处理输入的数据和运算符,并计算结果:
```
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 Calculator extends HttpServlet {
private static final long serialVersionUID = 1L;
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 "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
}
request.setAttribute("result", result);
request.getRequestDispatcher("Result.jsp").forward(request, response);
}
}
```
3. 最后,我们需要创建一个名为Result.jsp的JSP页面,用于显示计算结果:
```
<!DOCTYPE html>
<html>
<head>
<title>Result</title>
</head>
<body>
<h2>Result</h2>
<p>The result is: <%=request.getAttribute("result")%></p>
</body>
</html>
```
4. 部署应用程序并访问input.jsp页面,输入两个数和运算符,点击“Calculate”按钮,将会转到Result.jsp页面显示计算结果。
阅读全文