实现一个简单的投票系统可以分为以下步骤:
确定需求,设计数据库表结构
首先需要明确系统的功能需求以及相应的数据表结构,如投票主题、投票选项、投票结果等。可以使用MySQL、Oracle等数据库进行设计。
搭建开发环境
选择Eclipse、IntelliJ IDEA等Java开发工具,搭建相应的开发环境,并搭配相应的Web服务器,如Tomcat、Jetty等。
创建项目,配置web.xml
使用Maven创建Java web项目,然后在web.xml中配置Servlet、Filter、Listener等组件。
编写代码
通过Servlet接收用户请求,处理投票结果并存入数据库,然后再通过JSP将投票结果展示给用户。需要注意的是,为了防止用户重复投票,需要做好重复投票处理。
以下是具体实现步骤:
1. 创建数据库表结构
CREATE TABLE `vote_topic` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主题ID',
`title` varchar(100) NOT NULL COMMENT '主题名称',
`create_time` datetime NOT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `vote_item` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '投票选项ID',
`topic_id` int(11) NOT NULL COMMENT '主题ID',
`name` varchar(100) NOT NULL COMMENT '选项名称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `vote_result` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '结果ID',
`item_id` int(11) NOT NULL COMMENT '选项ID',
`create_time` datetime NOT NULL COMMENT '投票时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
2. 创建Java类
2.1 创建数据库连接池
/**
* 获取数据库连接池
*/
public class DBUtil {
public static DataSource getDataSource() {
// 使用C3P0连接池
return new ComboPooledDataSource();
}
}
2.2 创建投票主题类
/**
* 投票主题实体类
*/
public class VoteTopic {
private int id;
private String title;
private Date createTime;
private List<VoteItem> items;
// 省略getter和setter方法
}
2.3 创建投票选项类
/**
* 投票选项实体类
*/
public class VoteItem {
private int id;
private int topicId;
private String name;
private int voteCount;
// 省略getter和setter方法
}
2.4 创建投票结果类
/**
* 投票结果实体类
*/
public class VoteResult {
private int id;
private int itemId;
private Date createTime;
// 省略getter和setter方法
}
2.5 创建投票结果列表类
/**
* 投票结果列表实体类
*/
public class VoteResultList {
private int id;
private String name;
private int voteCount;
// 省略getter和setter方法
}
2.6 创建投票服务类
@WebServlet("/vote")
public class VoteServlet extends HttpServlet {
private static DataSource dataSource;
@Override
public void init() throws ServletException {
// 初始化数据库连接池
dataSource = DBUtil.getDataSource();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String voteItemId = request.getParameter("itemId");
int itemId = Integer.parseInt(voteItemId);
// 判断当前IP是否已经投过票
String ip = IPUtil.getIP(request);
boolean hasVoted = checkVoted(ip);
if (hasVoted) {
response.getWriter().write("您已经投过票了,每个IP只能投一次");
} else {
// 插入投票结果
insertVoteResult(itemId);
// 更新选项投票数
updateVoteCount(itemId);
response.sendRedirect("/vote/result");
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取投票主题
VoteTopic topic = getVoteTopic();
request.setAttribute("topic", topic);
request.getRequestDispatcher("/WEB-INF/jsp/vote.jsp").forward(request, response);
}
/**
* 获取投票主题
*/
private VoteTopic getVoteTopic() {
try (Connection conn = dataSource.getConnection()) {
String sql = "SELECT * FROM vote_topic WHERE id = 1";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
VoteTopic topic = new VoteTopic();
topic.setId(rs.getInt("id"));
topic.setTitle(rs.getString("title"));
topic.setCreateTime(rs.getTimestamp("create_time"));
// 获取投票选项列表
List<VoteItem> itemList = new ArrayList<>();
topic.setItems(itemList);
String itemSql = "SELECT * FROM vote_item WHERE topic_id = ?";
try (PreparedStatement itemStmt = conn.prepareStatement(itemSql)) {
itemStmt.setInt(1, topic.getId());
try (ResultSet itemRs = itemStmt.executeQuery()) {
while (itemRs.next()) {
VoteItem item = new VoteItem();
itemList.add(item);
item.setId(itemRs.getInt("id"));
item.setName(itemRs.getString("name"));
item.setVoteCount(itemRs.getInt("vote_count"));
}
}
}
return topic;
}
}
}
} catch (SQLException e) {
throw new RuntimeException("获取投票主题失败", e);
}
return null;
}
/**
* 插入投票结果
*/
private void insertVoteResult(int itemId) {
try (Connection conn = dataSource.getConnection()) {
String sql = "INSERT INTO vote_result (item_id, create_time) VALUES (?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, itemId);
stmt.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
stmt.executeUpdate();
}
} catch (SQLException e) {
throw new RuntimeException("插入投票结果失败", e);
}
}
/**
* 更新选项投票数
*/
private void updateVoteCount(int itemId) {
try (Connection conn = dataSource.getConnection()) {
String sql = "UPDATE vote_item SET vote_count = vote_count + 1 WHERE id = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, itemId);
stmt.executeUpdate();
}
} catch (SQLException e) {
throw new RuntimeException("更新投票选项数失败", e);
}
}
/**
* 检查当前IP是否已经投过票
*/
private boolean checkVoted(String ip) {
try (Connection conn = dataSource.getConnection()) {
String sql = "SELECT count(*) AS count FROM vote_result WHERE ip = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, ip);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
int count = rs.getInt("count");
return count > 0;
}
}
}
} catch (SQLException e) {
throw new RuntimeException("检查是否已经投过票失败", e);
}
return false;
}
/**
* 获取投票结果列表
*/
public List<VoteResultList> getVoteResultList() {
try (Connection conn = dataSource.getConnection()) {
String sql = "SELECT vote_item.id, vote_item.name, vote_item.vote_count FROM vote_item ORDER BY vote_item.vote_count DESC";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
try (ResultSet rs = stmt.executeQuery()) {
List<VoteResultList> resuts = new ArrayList<>();
while (rs.next()) {
VoteResultList voteResultList = new VoteResultList();
voteResultList.setId(rs.getInt("id"));
voteResultList.setName(rs.getString("name"));
voteResultList.setVoteCount(rs.getInt("vote_count"));
resuts.add(voteResultList);
}
return resuts;
}
}
} catch (SQLException e) {
throw new RuntimeException("获取投票结果列表失败", e);
}
}
}
3. 创建JSP页面
3.1 主页
<%@page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>投票系统首页</title>
</head>
<body>
<h1>投票主题:<c:out value="${topic.title}" /></h1>
<form method="POST" action="/vote">
<% for (VoteItem item : topic.getItems()) { %>
<input type="radio" name="itemId" value="<c:out value="${item.id}"/>" /><c:out value="${item.name}"/> <br />
<% } %>
<input type="submit" value="投票" />
</form>
</body>
</html>
3.2 投票结果页
<%@page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>投票结果</title>
</head>
<body>
<h1>投票结果</h1>
<table>
<tr>
<th>选项名称</th>
<th>投票数</th>
</tr>
<% List<VoteResultList> resultLists = new VoteServlet().getVoteResultList(); %>
<% for (VoteResultList resultList : resultLists) { %>
<tr>
<td><c:out value="${resultList.name}" /></td>
<td><c:out value="${resultList.voteCount}" /></td>
</tr>
<% } %>
</table>
</body>
</html>
以上示例代码仅为草稿代码,仅供参考,具体实现还需根据实际需求进行更改。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:javaweb实现投票系统 - Python技术站