开发一个动态网页计算器JSP服务应用,该服务页面能帮用户实现动态加、减、乘、除、求余计算。代码
时间: 2023-11-26 12:04:10 浏览: 84
好的,下面是一个简单的动态网页计算器JSP服务应用的代码示例,包括JSP页面和Servlet代码:
1. JSP页面(calculator.jsp):
```jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>动态网页计算器</title>
<script type="text/javascript">
function calculate(operator) {
var num1 = document.getElementById("num1").value.trim();
var num2 = document.getElementById("num2").value.trim();
if (num1 == "" || num2 == "") {
alert("请输入数字!");
return false;
}
var result = "";
switch (operator) {
case "+":
result = parseInt(num1) + parseInt(num2);
break;
case "-":
result = parseInt(num1) - parseInt(num2);
break;
case "*":
result = parseInt(num1) * parseInt(num2);
break;
case "/":
if (parseInt(num2) == 0) {
alert("除数不能为0!");
return false;
}
result = parseInt(num1) / parseInt(num2);
break;
case "%":
result = parseInt(num1) % parseInt(num2);
break;
default:
alert("非法操作符!");
return false;
}
document.getElementById("result").value = result;
}
</script>
</head>
<body>
<h1>动态网页计算器</h1>
<form action="CalculatorServlet" method="post">
<input type="text" id="num1" name="num1" placeholder="请输入第一个数" /><br />
<input type="text" id="num2" name="num2" placeholder="请输入第二个数" /><br /><br />
<input type="button" value="+" onclick="calculate('+')" />
<input type="button" value="-" onclick="calculate('-')" />
<input type="button" value="*" onclick="calculate('*')" />
<input type="button" value="/" onclick="calculate('/')" />
<input type="button" value="%" onclick="calculate('%')" /><br /><br />
<input type="text" id="result" name="result" placeholder="计算结果" readonly /><br /><br />
<input type="submit" value="提交" />
<input type="reset" value="重置" />
</form>
</body>
</html>
```
2. Servlet代码(CalculatorServlet.java):
```java
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 {
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 result = request.getParameter("result");
request.setAttribute("num1", num1);
request.setAttribute("num2", num2);
request.setAttribute("result", result);
request.getRequestDispatcher("calculator.jsp").forward(request, response);
}
}
```
这段代码实现了一个简单的动态网页计算器,用户可以在JSP页面中输入两个数并选择运算符,点击“提交”按钮后,Servlet会根据用户选择的运算符进行计算,并将结果返回给JSP页面显示。
阅读全文