《Java系列-开发相关》基于JavaWeb的简易投票系统
基于JavaWeb的简易投票系统1.工具IDEAJDK1.8Tomcat8.5MySQL2.MySQL数据库subjects表/*Navicat Premium Data TransferSource Server: zxySource Server Type: MySQLSource Server Version : 50710Source Host: localhost:3306Source
·
基于JavaWeb的简易投票系统
1.工具
IDEA
JDK1.8
Tomcat8.5
MySQL
2.MySQL数据库
- subjects表
/*
Navicat Premium Data Transfer
Source Server : zxy
Source Server Type : MySQL
Source Server Version : 50710
Source Host : localhost:3306
Source Schema : java_test
Target Server Type : MySQL
Target Server Version : 50710
File Encoding : 65001
Date: 19/06/2021 16:16:30
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for subjects
-- ----------------------------
DROP TABLE IF EXISTS `subjects`;
CREATE TABLE `subjects` (
`id` int(10) NOT NULL COMMENT '主题ID',
`title` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '主题名',
`totalVotes` int(50) NOT NULL COMMENT '投票人数',
`viewTimes` int(50) NOT NULL COMMENT '查看次数',
`createDate` date NOT NULL COMMENT '创建时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of subjects
-- ----------------------------
INSERT INTO `subjects` VALUES (1, '本次考试难度如何', 30, 100, '2021-06-18');
INSERT INTO `subjects` VALUES (2, '导致空气污染得主要原因是什么', 40, 200, '2021-06-18');
INSERT INTO `subjects` VALUES (3, '你幸福吗', 35, 150, '2021-06-18');
SET FOREIGN_KEY_CHECKS = 1;
- options表
/*
Navicat Premium Data Transfer
Source Server : zxy
Source Server Type : MySQL
Source Server Version : 50710
Source Host : localhost:3306
Source Schema : java_test
Target Server Type : MySQL
Target Server Version : 50710
File Encoding : 65001
Date: 19/06/2021 16:16:38
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for options
-- ----------------------------
DROP TABLE IF EXISTS `options`;
CREATE TABLE `options` (
`id` int(10) NOT NULL COMMENT '选项ID',
`optContent` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '选项内容',
`vote` int(50) NOT NULL COMMENT '得票数',
`sid` int(50) NOT NULL COMMENT '主题ID,主题表外键',
PRIMARY KEY (`id`) USING BTREE,
INDEX `sid`(`sid`) USING BTREE,
CONSTRAINT `sid` FOREIGN KEY (`sid`) REFERENCES `subjects` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of options
-- ----------------------------
INSERT INTO `options` VALUES (1, '很难', 5, 1);
INSERT INTO `options` VALUES (2, '比较难', 10, 1);
INSERT INTO `options` VALUES (3, '一般', 5, 1);
INSERT INTO `options` VALUES (4, '容易', 3, 1);
INSERT INTO `options` VALUES (5, '很容易', 7, 1);
SET FOREIGN_KEY_CHECKS = 1;
3.准备工作
-
tomcat
-
mybatis-3-cfg.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/java_test?useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 让主配置文件引用映射配置文件 -->
<mappers>
<mapper resource="com/zxy/mapper/UserMapper.xml"/>
</mappers>
</configuration>
- lib
Project Structure --》Modoules --》 Dependencies --》点击“+”添加JARS,选中lib目录就可以
JSP页面
- index.jsp
<%@ page import="com.zxy.pojo.Subjects" %>
<%@ page import="java.util.List" %>
<%--
Created by IntelliJ IDEA.
User: ZXY
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主题页面</title>
</head>
<body>
<a href="SubjectServlet">投票系统</a>
</body>
</html>
- show.jsp
<%@ page import="com.zxy.pojo.Subjects" %>
<%@ page import="java.util.List" %>
<%--
Created by IntelliJ IDEA.
User: ZXY
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主题页面</title>
</head>
<body>
<a href="/SubjectServlet">全部主题 >></a>
<%-- <div style="text-align: center">全部主题 >></div>--%>
<form action="/OptionServlet" method="post">
<table border="1">
<tr>
<th>序号</th>
<th>主题</th>
<th>投票/查看</th>
<th>创建时间</th>
</tr>
<%
List<Subjects> subjects = (List<Subjects>) session.getAttribute("subjects");
for(Subjects lists:subjects){
%>
<tr>
<td><%=lists.getId()%></td>
<td>
<input type="submit" value="<%=lists.getTitle()%>">
</td>
<td><%=lists.getTotalVotes()%>/<%=lists.getViewTimes()%></td>
<td><%=lists.getCreateDate()%></td>
</tr>
<%
}
%>
</table>
</form>
</body>
</html>
- Option.jsp
<%@ page import="com.zxy.pojo.Options" %>
<%@ page import="java.util.List" %>
<%@ page import="com.zxy.pojo.Subjects" %><%--
Created by IntelliJ IDEA.
User: ZXY
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>投票选项</title>
</head>
<body>
<h2>本次投票难度如何</h2>
<%
List<Subjects> subjects = (List<Subjects>) session.getAttribute("subject");
for(Subjects list:subjects){
if(list.getId() == 1){
%>
<h3><%=list.getViewTimes()%>次查看,共有<%=list.getTotalVotes()%>人投票</h3>
<%
}
}
%>
<form action="/UpdateVoteServlet" method="post" id="updateVotes">
<table border="1">
<tr>
<th>序号</th>
<th>选项</th>
<th>票数</th>
<th>投票率</th>
</tr>
<%
List<Options> Options = (List<Options>) session.getAttribute("option");
subjects = (List<Subjects>) session.getAttribute("subject");
for(Subjects sub : subjects){
if(sub.getId() == 1){
int sumVote = sub.getTotalVotes();
System.out.println("sumvote");
System.out.println(sumVote);
for(Options lists:Options){
double sum = ((double)lists.getVote()/(double)sumVote) * 100;
long round = Math.round(sum * 100);
double s = round / 100.0;
System.out.println("lists.getvote()");
System.out.println(lists.getVote());
System.out.println("s");
System.out.println(s);
%>
<tr>
<td><%=lists.getId()%></td>
<td><%=lists.getOptContent()%></td>
<td><%=lists.getVote()%></td>
<td><%=s%>%</td>
</tr>
<%
}
}
}
%>
</table>
投票选项<input type="text" name="id" id="id"><br>
<span id="msg" style="font-size: 12px;color: red">${messageModel.msg}</span> <br>
<button type="button" id="loginBtn" >投票</button>
</form>
</body>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
$("#loginBtn").click(function () {
var id = $("#id").val();
if(isEmpty(id)){
$("#msg").html("投票选项不能为空!");
return;
}
$("#updateVotes").submit()
});
/**
* 判断用户名或者密码为空的函数
*/
function isEmpty(str) {
if(str == null || str.trim() == ""){
return true;
}
return false;
}
</script>
</html>
</html>
- Votes.jsp
<%@ page import="com.zxy.pojo.Options" %>
<%@ page import="java.util.List" %>
<%@ page import="com.zxy.pojo.Subjects" %><%--
Created by IntelliJ IDEA.
User: ZXY
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>投票选项</title>
</head>
<body>
<form action="/UpdateVoteServlet" method="post">
<table border="1">
<tr>
<th>序号</th>
<th>选项</th>
<th>票数</th>
<th>投票率</th>
</tr>
<%
List<Options> Options = (List<Options>) session.getAttribute("option");
List<Subjects> subjects = (List<Subjects>) session.getAttribute("subject");
for(Subjects sub : subjects){
if(sub.getId() == 1){
int sumVote = sub.getTotalVotes();
System.out.println("sumvote");
System.out.println(sumVote);
for(Options lists:Options){
double sum = ((double)lists.getVote()/(double)sumVote) * 100;
long round = Math.round(sum * 100);
double s = round / 100.0;
System.out.println("lists.getvote()");
System.out.println(lists.getVote());
System.out.println("s");
System.out.println(s);
%>
<tr>
<td><%=lists.getId()%></td>
<td><%=lists.getOptContent()%></td>
<td><%=lists.getVote()%></td>
<td><%=s%>%</td>
</tr>
<%
}
}
}
%>
</table>
</form>
<a href="/show.jsp"><input type="button" value="返回主题页面"></a>
</body>
</html>
- web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>SubjectServlet</servlet-name>
<servlet-class>com.zxy.controller.SubjectServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SubjectServlet</servlet-name>
<url-pattern>/SubjectServlet</url-pattern><!-- 访问servlet的路径 -->
</servlet-mapping>
<servlet>
<servlet-name>OptionServlet</servlet-name>
<servlet-class>com.zxy.controller.OptionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>OptionServlet</servlet-name>
<url-pattern>/OptionServlet</url-pattern><!-- 访问servlet的路径 -->
</servlet-mapping>
<servlet>
<servlet-name>UpdateVoteServlet</servlet-name>
<servlet-class>com.zxy.controller.UpdateVoteServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UpdateVoteServlet</servlet-name>
<url-pattern>/UpdateVoteServlet</url-pattern><!-- 访问servlet的路径 -->
</servlet-mapping>
</web-app>
JavaWeb
mapper
- UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
从现在开始不能随便
namespace : mapper配置文件对应的mapper接口的包名.类名
id : mapper接口中对应的方法名称
-->
<mapper namespace="com.zxy.mapper.UserMapper">
<!-- 映射配置文件用于专门写sql,查询所有的员工信息 -->
<select id="queryUserByName" parameterType="String" resultType="com.zxy.pojo.User">
select * from tb_user where userName = #{uname}
</select>
<select id="queryAllSubject" resultType="com.zxy.pojo.Subjects">
SELECT * FROM `subjects`
</select>
<select id="queryAllOption" resultType="com.zxy.pojo.Options">
SELECT * FROM `options`
</select>
<select id="updateOptionVote" resultType="com.zxy.pojo.Options">
update `options` set vote=vote+1 where id = #{id}
</select>
</mapper>
- UserMapper.java
package com.zxy.mapper;
import com.zxy.pojo.Options;
import com.zxy.pojo.Subjects;
import com.zxy.pojo.User;
import java.util.List;
public interface UserMapper {
/**
* UserMapper.xml
* <select id="queryUserByName" parameterType="String" resultType="com.zxy.entity.User">
* User,queryUserByName,String
* 类型,名称,返回值类型
* @param uname
* @return
*/
public User queryUserByName(String uname);
/**
* <select id="queryAllSubject" resultType="com.zxy.pojo.Subjects">
* SELECT * FROM `subjects`
* </select>
*/
List<Subjects> queryAllSubject();
List<Options> queryAllOption();
List<Options> updateOptionVote(String id);
}
service
- SubjectServiceImpl
package com.zxy.service.impl;
import com.zxy.mapper.UserMapper;
import com.zxy.pojo.Options;
import com.zxy.pojo.Subjects;
import com.zxy.service.SubjectService;
import com.zxy.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class SubjectServiceImpl implements SubjectService {
SqlSession sqlSession = MybatisUtils.getSqlSession();
private UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
public List<Subjects> findAllSubject() {
return userMapper.queryAllSubject();
}
public List<Options> findAllOption() {
return userMapper.queryAllOption();
}
public List<Options> updateOptionVote(String id) {
return userMapper.updateOptionVote(id);
}
}
- subjectService.java
package com.zxy.service;
import com.zxy.pojo.Options;
import com.zxy.pojo.Subjects;
import java.util.List;
public interface SubjectService {
List<Subjects> findAllSubject();
List<Options> findAllOption();
List<Options> updateOptionVote(String id);
}
controller
- SubjectServlet.java
package com.zxy.controller;
import com.zxy.pojo.Subjects;
import com.zxy.service.SubjectService;
import com.zxy.service.impl.SubjectServiceImpl;
import javax.jws.WebService;
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 java.io.IOException;
import java.util.List;
/**
* 主题类的Servlet,读取数据库中数据,并返回给index.jsp
*/
public class SubjectServlet extends HttpServlet {
private SubjectService subjectService = new SubjectServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Subjects> subjects = subjectService.findAllSubject();
for (Subjects s:subjects) {
System.out.println(s.getTitle());
}
if(subjects != null) {
req.getSession().setAttribute("subjects", subjects);
resp.sendRedirect("show.jsp");
}else{
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Subjects> subjects = subjectService.findAllSubject();
for (Subjects s:subjects) {
System.out.println(s.getTitle());
}
if(subjects != null) {
request.getSession().setAttribute("subjects", subjects);
response.sendRedirect("show.jsp");
}else{
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
}
- Optionservlet.java
package com.zxy.controller;
import com.zxy.pojo.Options;
import com.zxy.pojo.Subjects;
import com.zxy.service.SubjectService;
import com.zxy.service.impl.SubjectServiceImpl;
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 java.io.IOException;
import java.util.List;
public class OptionServlet extends HttpServlet {
private SubjectService subjectService = new SubjectServiceImpl();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Options> option = subjectService.findAllOption();
List<Subjects> subject = subjectService.findAllSubject();
for(Options op:option){
System.out.println(op.getId());
}
request.getSession().setAttribute("subject", subject);
request.getSession().setAttribute("option", option);
response.sendRedirect("Option.jsp");
}
}
- UpdateVoteServlet.java
package com.zxy.controller;
import com.zxy.pojo.Options;
import com.zxy.pojo.Subjects;
import com.zxy.service.SubjectService;
import com.zxy.service.impl.SubjectServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
public class UpdateVoteServlet extends HttpServlet {
private SubjectService subjectService = new SubjectServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
List<Options> options = subjectService.updateOptionVote(id);
List<Subjects> subject = subjectService.findAllSubject();
List<Options> option = subjectService.findAllOption();
request.getSession().setAttribute("option", option);
request.getSession().setAttribute("subject", subject);
response.sendRedirect("Votes.jsp");
}
}
pojo
- Subjects.java
package com.zxy.pojo;
import java.util.Date;
public class Subjects {
private Integer id;
private String title;
private Integer totalVotes;
private Integer viewTimes;
private Date createDate;
public Subjects() {
}
public Subjects(Integer id, String title, Integer totalVotes, Integer viewTimes, Date createDate) {
this.id = id;
this.title = title;
this.totalVotes = totalVotes;
this.viewTimes = viewTimes;
this.createDate = createDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getTotalVotes() {
return totalVotes;
}
public void setTotalVotes(Integer totalVotes) {
this.totalVotes = totalVotes;
}
public Integer getViewTimes() {
return viewTimes;
}
public void setViewTimes(Integer viewTimes) {
this.viewTimes = viewTimes;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
@Override
public String toString() {
return "Subjects{" +
"id=" + id +
", title='" + title + '\'' +
", totalVotes=" + totalVotes +
", viewTimes=" + viewTimes +
", createDate=" + createDate +
'}';
}
}
- Options.java
package com.zxy.pojo;
public class Options {
private Integer id;
private String optContent;
private Integer vote;
private Integer sid;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOptContent() {
return optContent;
}
public void setOptContent(String optContent) {
this.optContent = optContent;
}
public Integer getVote() {
return vote;
}
public void setVote(Integer vote) {
this.vote = vote;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
}
utils
- MybatisUtils.java
package com.zxy.util;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MybatisUtils {
private static final String DEFAULT_CONFIG_XML = "mybatis-3-cfg.xml";
private static SqlSessionFactory sqlSessionFactory;
static {
sqlSessionFactory
= new SqlSessionFactoryBuilder().build(MybatisUtils.class.getClassLoader().getResourceAsStream(DEFAULT_CONFIG_XML));
}
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
public static void close(SqlSession sqlSession) {
if (sqlSession != null) sqlSession.close();
}
}
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献4条内容
所有评论(0)