编写一个jsp页面,设计一个投票表格,提交数据后保存到application中
时间: 2024-03-25 19:40:35 浏览: 22
好的,这是一个比较简单的任务,下面是jsp页面的代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>投票表格</title>
</head>
<body>
<h2>请选择您的喜欢的水果:</h2>
<form action="VoteServlet" method="post">
<table>
<tr>
<td><input type="radio" name="fruit" value="apple">苹果</td>
<td><input type="radio" name="fruit" value="banana">香蕉</td>
<td><input type="radio" name="fruit" value="orange">橙子</td>
<td><input type="radio" name="fruit" value="watermelon">西瓜</td>
</tr>
</table>
<br>
<input type="submit" value="提交">
</form>
</body>
</html>
```
上面的代码定义了一个简单的投票表格,其中有四个选项:苹果、香蕉、橙子和西瓜,用户可以选择其中一个选项并点击提交按钮。
当用户提交表单时,表单数据会被发送到名为"VoteServlet"的servlet中处理。下面是该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;
import javax.servlet.http.HttpSession;
public class VoteServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fruit = request.getParameter("fruit");
// 获取application对象
HttpSession session = request.getSession();
ServletContext application = session.getServletContext();
// 获取当前水果的投票数,如果不存在则初始化为0
Integer count = (Integer) application.getAttribute(fruit);
if (count == null) {
count = 0;
}
// 投票数加1
count++;
application.setAttribute(fruit, count);
// 跳转到投票结果页面
response.sendRedirect("result.jsp");
}
}
```
上面的代码从请求中获取用户选择的水果选项,然后将该选项的投票数加1,并将结果保存到application对象中。最后,将用户重定向到投票结果页面。
投票结果页面的代码示例如下:
```html
<!DOCTYPE html>
<html>
<head>
<title>投票结果</title>
</head>
<body>
<h2>投票结果:</h2>
<p>苹果: <%= application.getAttribute("apple") %> 票</p>
<p>香蕉: <%= application.getAttribute("banana") %> 票</p>
<p>橙子: <%= application.getAttribute("orange") %> 票</p>
<p>西瓜: <%= application.getAttribute("watermelon") %> 票</p>
</body>
</html>
```
上面的代码从application对象中获取每个水果的投票数,并将其显示在投票结果页面上。
这就是一个简单的jsp页面,可以用来收集投票数据并将其保存到application对象中。希望可以帮到你!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)