设计一个web应用,有两个jsp页面inputnumber.jsp
时间: 2024-03-22 21:37:23 浏览: 59
和result.jsp,其中inputnumber.jsp页面上有一个输入框,用户可以在输入框中输入一个数字,然后通过提交按钮将这个数字提交到后端服务器。后端服务器通过计算这个数字的阶乘,并将计算结果返回给result.jsp页面进行展示。
以下是一个简单的实现示例:
inputnumber.jsp:
```html
<html>
<head>
<title>输入数字</title>
</head>
<body>
<form action="calculate" method="post">
<label>请输入一个数字:</label>
<input type="text" name="number">
<input type="submit" value="提交">
</form>
</body>
</html>
```
result.jsp:
```html
<html>
<head>
<title>计算结果</title>
</head>
<body>
<h1>计算结果为:<%= result %></h1>
</body>
</html>
```
Servlet代码:
```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 CalculateServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String numberStr = request.getParameter("number");
int number = Integer.parseInt(numberStr);
int result = calculateFactorial(number);
request.setAttribute("result", result);
request.getRequestDispatcher("result.jsp").forward(request, response);
}
private int calculateFactorial(int number) {
int result = 1;
for (int i = 1; i <= number; i++) {
result *= i;
}
return result;
}
}
```
在web.xml中配置Servlet:
```xml
<servlet>
<servlet-name>CalculateServlet</servlet-name>
<servlet-class>com.example.CalculateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CalculateServlet</servlet-name>
<url-pattern>/calculate</url-pattern>
</servlet-mapping>
```
这样,当用户在inputnumber.jsp页面中输入一个数字并提交时,就会调用CalculateServlet的doPost方法,计算阶乘并将结果保存在request中,然后将请求转发到result.jsp页面展示计算结果。
阅读全文