使用Servlet+JSP实现简单的计算器功能;
时间: 2024-09-25 07:14:11 浏览: 43
使用Servlet + JSP实现简单的计算器功能通常涉及以下几个步骤:
1. 创建Servlet:首先,在Java项目中创建一个新的Servlet,比如CalculatorServlet.java。这个Servlet将处理用户的请求,接收输入的数字和操作符,并返回计算结果。
```java
import javax.servlet.*;
import java.io.*;
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");
// 对输入进行验证并进行相应的运算
double result;
if (operator.equals("+")) {
result = Double.parseDouble(num1) + Double.parseDouble(num2);
} else if (operator.equals("-")) {
result = Double.parseDouble(num1) - Double.parseDouble(num2);
} else if (operator.equals("*")) {
result = Double.parseDouble(num1) * Double.parseDouble(num2);
} else if (operator.equals("/")) {
result = Double.parseDouble(num1) / Double.parseDouble(num2);
} else {
result = "Invalid operator";
}
// 将结果设置到响应中
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("Result: " + result);
out.println("</body></html>");
}
}
```
2. 配置Servlet:在web.xml文件中配置Servlet,指定Servlet的URL映射和它对应的类。
```xml
< servlet >
< servlet-name > CalculatorServlet </ servlet-name >
< servlet-class > CalculatorServlet </ servlet-class >
</ servlet >
<servlet-mapping>
<servlet-name>CalculatorServlet</servlet-name>
<url-pattern>/calculator</url-pattern>
</servlet-mapping>
```
3. 创建JSP页面:创建一个名为calculator.jsp的JSP页面,用于接收用户输入、显示结果以及提交表单。可以使用HTML表单元素。
```jsp
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
</head>
<body>
<form action="CalculatorServlet" method="post">
Number 1: <input type="number" name="num1"><br>
Number 2: <input type="number" name="num2"><br>
Operator: <select name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select><br>
<input type="submit" value="Calculate">
</form>
<%@ include file="result.jsp" %>
</body>
</html>
```
4. 结果页面:创建一个result.jsp文件,用于接收并显示计算结果。
```jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<h1>Result:</h1>
<p>${result}</p>
```
阅读全文