以下是一个简易的JSP和Servlet相结合的计算器示例。假设我们有两个文本框用于输入数字,一个下拉列表用于选择运算符,并有一个按钮来提交表单并显示结果。
JSP页面(calculator.jsp)
<!DOCTYPE html>
<html>
<head>
<title>简易计算器</title>
</head>
<body>
<form action="CalculatorServlet" method="POST">
数字1: <input type="text" name="number1" /><br/>
数字2: <input type="text" name="number2" /><br/>
运算符:
<select name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select><br/>
<input type="submit" value="计算" />
</form>
<br/>
<% if (request.getAttribute("result") != null) { %>
结果: <%= request.getAttribute("result") %>
<% } %>
</body>
</html>
Servlet类(CalculatorServlet.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 {
String number1Str = request.getParameter("number1");
String number2Str = request.getParameter("number2");
String operator = request.getParameter("operator");
double number1 = Double.parseDouble(number1Str);
double number2 = Double.parseDouble(number2Str);
double result = 0;
switch (operator) {
case "+":
result = number1 + number2;
break;
case "-":
result = number1 - number2;
break;
case "*":
result = number1 * number2;
break;
case "/":
if (number2 != 0) {
result = number1 / number2;
} else {
response.getWriter().write("除数不能为0");