基于Servlet的MVC模式设计一个简单web应用:实现简单加减乘除运算的计算器。
时间: 2024-04-03 14:31:07 浏览: 134
好的,以下是基于Servlet的MVC模式设计的简单加减乘除运算的计算器示例:
首先,我们需要创建一个Model类Calculator,用于进行四则运算:
```java
public class Calculator {
public int add(int num1, int num2) {
return num1 + num2;
}
public int subtract(int num1, int num2) {
return num1 - num2;
}
public int multiply(int num1, int num2) {
return num1 * num2;
}
public int divide(int num1, int num2) {
return num1 / num2;
}
}
```
然后,我们需要创建一个View类CalculatorView,用于渲染页面:
```java
public class CalculatorView {
public void render(HttpServletRequest request, HttpServletResponse response, String result) throws ServletException, IOException {
request.setAttribute("result", result);
request.getRequestDispatcher("calculator.jsp").forward(request, response);
}
}
```
在View类中,我们使用了JSP页面calculator.jsp,用于渲染页面并显示计算结果:
```html
<html>
<head>
<title>Calculator</title>
</head>
<body>
<h1>Calculator</h1>
<form action="calculator" method="post">
<input type="text" name="num1" placeholder="Enter first number" required>
<select name="operator">
<option value="add">+</option>
<option value="subtract">-</option>
<option value="multiply">*</option>
<option value="divide">/</option>
</select>
<input type="text" name="num2" placeholder="Enter second number" required>
<input type="submit" value="Calculate">
</form>
<h2>Result: <%= request.getAttribute("result") %></h2>
</body>
</html>
```
接着,我们需要创建一个Controller类CalculatorController,用于处理请求并调用Model和View:
```java
public class CalculatorController extends HttpServlet {
private Calculator calculator;
private CalculatorView calculatorView;
public void init() {
calculator = new Calculator();
calculatorView = new CalculatorView();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
calculatorView.render(request, response, "");
}
public 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 "add":
result = calculator.add(num1, num2);
break;
case "subtract":
result = calculator.subtract(num1, num2);
break;
case "multiply":
result = calculator.multiply(num1, num2);
break;
case "divide":
result = calculator.divide(num1, num2);
break;
}
calculatorView.render(request, response, String.valueOf(result));
}
}
```
在Controller类中,我们首先实例化了Calculator和CalculatorView类,然后在doGet方法中渲染页面,而在doPost方法中获取用户输入的数据,调用Model类进行计算,然后将结果传递给View类进行渲染。
最后,我们需要在web.xml中配置Servlet:
```xml
<servlet>
<servlet-name>CalculatorController</servlet-name>
<servlet-class>com.example.CalculatorController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CalculatorController</servlet-name>
<url-pattern>/calculator</url-pattern>
</servlet-mapping>
```
现在,我们就可以通过访问http://localhost:8080/calculator来使用我们的简单加减乘除运算的计算器了。
阅读全文