请给出基于Java、mysql、tomcat、html的web候选人投票系统的详细代码
时间: 2023-07-10 13:37:08 浏览: 102
好的,以下是基于Java、MySQL、Tomcat和HTML的Web候选人投票系统的详细代码示例:
1. 数据库设计
创建数据库vote,其中包括两个表格candidate和vote_record。
```mysql
CREATE DATABASE vote;
USE vote;
CREATE TABLE candidate (
id INT(11) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
photo VARCHAR(100),
description VARCHAR(255)
);
CREATE TABLE vote_record (
id INT(11) PRIMARY KEY AUTO_INCREMENT,
user_id INT(11) NOT NULL,
candidate_id INT(11) NOT NULL,
vote_time DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES user(id),
FOREIGN KEY (candidate_id) REFERENCES candidate(id)
);
```
2. Java Web项目搭建
创建一个新的Java Web项目vote_system,添加如下依赖:
- MySQL JDBC驱动
- Tomcat Servlet API
- JSP API
创建一个名为DBUtil的Java类,用于封装数据库操作。
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtil {
private static final String URL = "jdbc:mysql://localhost:3306/vote?useSSL=false&serverTimezone=UTC";
private static final String USER = "root";
private static final String PASSWORD = "password";
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void close(Connection conn, PreparedStatement pstmt, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
3. 用户登录
创建一个名为LoginServlet的Servlet,用于处理用户登录请求。
```java
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
pstmt = conn.prepareStatement("SELECT id FROM user WHERE username=? AND password=?");
pstmt.setString(1, username);
pstmt.setString(2, password);
rs = pstmt.executeQuery();
if (rs.next()) {
HttpSession session = request.getSession();
session.setAttribute("user_id", rs.getInt("id"));
response.sendRedirect("candidate_list.jsp");
} else {
response.sendRedirect("login.jsp?error=1");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, pstmt, rs);
}
}
}
```
4. 候选人列表
创建一个名为CandidateListServlet的Servlet,用于获取候选人列表并在JSP页面中展示。
```java
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/candidate_list")
public class CandidateListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
pstmt = conn.prepareStatement("SELECT id, name, photo, description FROM candidate");
rs = pstmt.executeQuery();
List<Candidate> candidates = new ArrayList<Candidate>();
while (rs.next()) {
Candidate candidate = new Candidate();
candidate.setId(rs.getInt("id"));
candidate.setName(rs.getString("name"));
candidate.setPhoto(rs.getString("photo"));
candidate.setDescription(rs.getString("description"));
candidates.add(candidate);
}
request.setAttribute("candidates", candidates);
request.getRequestDispatcher("candidate_list.jsp").forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, pstmt, rs);
}
}
}
```
5. 投票
创建一个名为VoteServlet的Servlet,用于处理用户投票请求。
```java
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/vote")
public class VoteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int candidateId = Integer.parseInt(request.getParameter("candidate_id"));
HttpSession session = request.getSession();
int userId = (int) session.getAttribute("user_id");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
pstmt = conn.prepareStatement("SELECT id FROM vote_record WHERE user_id=? AND candidate_id=?");
pstmt.setInt(1, userId);
pstmt.setInt(2, candidateId);
rs = pstmt.executeQuery();
if (rs.next()) {
response.sendRedirect("candidate_list.jsp?error=1");
} else {
pstmt = conn.prepareStatement("INSERT INTO vote_record (user_id, candidate_id) VALUES (?, ?)");
pstmt.setInt(1, userId);
pstmt.setInt(2, candidateId);
pstmt.executeUpdate();
response.sendRedirect("candidate_list.jsp");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, pstmt, rs);
}
}
}
```
6. JSP页面
最后创建一个名为candidate_list.jsp的JSP页面,用于展示候选人列表并处理用户投票请求。
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>候选人列表</title>
<style type="text/css">
.candidate {
margin: 10px;
padding: 10px;
border: 1px solid #ddd;
display: inline-block;
text-align: center;
vertical-align: top;
}
.candidate img {
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<h1>候选人列表</h1>
<c:if test="${not empty param.error}">
<p style="color: red;">您已经投过票了,请勿重复投票!</p>
</c:if>
<c:forEach var="candidate" items="${candidates}">
<div class="candidate">
<img src="${candidate.photo}" />
<p>${candidate.name}</p>
<p>${candidate.description}</p>
<form method="post" action="vote">
<input type="hidden" name="candidate_id" value="${candidate.id}" />
<button type="submit">投票</button>
</form>
</div>
</c:forEach>
</body>
</html>
```
以上是基于Java、MySQL、Tomcat和HTML的Web候选人投票系统的详细代码示例。希望能对您有所帮助。
阅读全文