JSP implements online voting system

System introduction
The development and growth of a website depends on the support of many users. A good website must pay attention to the exchange of information with users, get feedback from users in time, and improve it in time. This is also the basis for the sustainable development of a website. It is also for this reason that various voting systems emerge in an endless stream on the Internet. The next project is to compile an online voting system, which can accumulate votes, query and count votes, and other operations.
Operation Precautions
1.When conducting voting operations, only one vote can be cast within an hour.
The renderings show:
write picture description here
write picture description here
write picture description here

The code is as follows:
Database building database building table code:

create database votedb;
create table users(
    id int(10) auto_increment primary key,
    ip varchar(20) not null,
    lastTime long(8) not null
);
create table vote(
    id int(10) auto_increment primary key,
    title varchar(50) not null,
    num int not null
);
insert into users(ip, lastTime) values
    ('001',1),
    ('002',2),
    ('003',3),
    ('004',4);
insert into vote(title, num) values
    ('潘玮柏',20),
    ('周杰伦',30),
    ('justin',40),
    ('杨非同',25);

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>在线投票系统</title>
</head>
<body>
    <h1>在线投票系统</h1>
    <div>
        <a href = "vote.jsp"><input type ="button" value = "在线投票"/></a>
        <br/>
        <a href = "showVote.jsp"><input type ="button" value = "投票结果"/></a>
    </div>

</body>
</html>

vote.jsp

<%@page import="com.valuebean.UserSingle"%>
<%@page import="com.valuebean.voteSingle"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.sql.ResultSet"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<jsp:useBean id="db" class = "com.database.DB" scope = "session"></jsp:useBean>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
    .a{
        border: 1px solid;
    }
</style>
<title>在线投票</title>
</head>
<body>
    <form action="doVote.jsp" method = "post">
    <table>
    <%
        ArrayList<voteSingle> votes = db.getVotes();
        if(votes == null || votes.size() == 0){
    %>
            <tr>
                <td>无内容可以显示</td>
            </tr>
    <%
        }else{
            for(int i = 0, length = votes.size(); i < length; i++){
    %>
    <tr class = "a">
        <td class = "a">
            <%= votes.get(i).getTitle() %>
        </td>
        <td class = "a">
            <input type = "radio" name = "like" value="<%=votes.get(i).getId()%>"></input>
        </td>
    </tr>
        <br/>
    <%
        }
    }
    %>
    <tr>
        <td>
            <input type = "submit" value = "提交"/>
        </td>
        <td>
            <input type = "reset" value = "重置"/>
        </td>
        <td>
            <a href = "index.jsp">
                <input type = "button" value = "返回主界面">
            </a>
        </td>
        <td>
            <a href = "showVote.jsp">
                <input type = "button" value = "显示投票结果">
            </a>
        </td>
    </tr>
    </table>
    </form>
</body>
</html>

dovote.jsp

<%@page import="com.valuebean.voteSingle"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.util.Date"%>
<%@page import="com.valuebean.UserSingle"%>
<%@page import="com.toolbean.MyTool"%>
<jsp:useBean id="db" class = "com.database.DB" scope = "session"></jsp:useBean>
<%
    long cc = 0, dd = 0;
    int id = MyTool.strToInt(request.getParameter("like"));
    int flag = -1, i = -1;
    String sql = "";
    Date date = new Date();
    long today = date.getTime();
    voteSingle v =db.findvote(id);
    String mes = "";
    long lastTime = 0;
    String ip = "005";
    //String ip = request.getRemoteAddr();
    UserSingle u = db.findUser(ip);
    if(u == null){
        u = new UserSingle();
        u.setIp(ip);
        u.setLastTime(today);
        flag = 0;
    }else{
        lastTime = u.getLastTime();
        cc = today;
        dd = lastTime;
        if((today - lastTime) >= 60 * 60 * 1000){
            flag  = 1;
        }else{
            flag = 2;
        }
    }
    if(flag == 0){
        sql = "insert into users(ip, lastTime) values('"+ip+"','+"+today+"')";
        i = db.update(sql);
        if(i < 0){
            System.out.println("插入user失败!");
            i = -1;
        }
        sql = "update vote set num=num+1 where id="+id;
        i = db.update(sql);
        if(i < 0){
            System.out.println("更新vote表失败(num+1)");
            i = -1;
        }
    }
    if(flag == 1){
        sql = "update vote set num=num+1 where id="+id;
        i = db.update(sql);
        if(i < 0){
            System.out.println("更新vote表失败(num+1)");
            i = -1;
        }
        sql = "update users set lastTime ="+today+" where ip= '"+ip+ "'";
        i = db.update(sql);
        if(i < 0){
            System.out.println("更新user表失败lastTime=today");
            i = -1;
        }
    }
    if(flag == 2){
        mes = u.getIp()+" 为  "+v.getTitle()+" 投票失败,距离上一次投票不足一小时,上一次投票时间为"+MyTool.formatDate(lastTime);
    }
    if(flag == 1){
        mes = u.getIp()+" 为  "+v.getTitle()+" 投票成功,当前投票时间为:" + MyTool.formatDate(today);
    }
    if(flag == 0){
        mes = u.getIp()+" 为 "+v.getTitle()+" 首次投票成功,当前投票时间为:" + MyTool.formatDate(today);
    }
    session.setAttribute("mes", mes);
    response.sendRedirect("message.jsp");
%>

message.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%
  String message=(String)session.getAttribute("mes");
  session.invalidate();
%>
<html>
    <head>
        <title>友情提示</title>     
    </head>
    <body bgcolor="#F0F0F0">
      <table>
        <tr>
            <td>
                <%=message %>
            </td>
        </tr>
        <tr height="114">
           <td align="center" valign="top">
               <a href="index.jsp"><input type = "button" value = "返回首页"></a>
               <a href="vote.jsp"><input type = "button" value = "继续投票"></a>
               <a href="showVote.jsp"><input type = "button" value = "查看结果"></a>
           </td>
        </tr>
      </table>
    </body>
</html>

showVote.jsp

<%@page import="com.toolbean.MyTool"%>
<%@page import="com.valuebean.voteSingle"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<jsp:useBean id="db" class = "com.database.DB" scope = "session"></jsp:useBean>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>投票结果</title>
</head>
<body>
        <table>
    <%
        ArrayList<voteSingle> votes = db.getVotes();
        int numAll = 0;
        float picLen = 0;
        if(votes == null || votes.size() == 0){
    %>
            <tr>
                <td>无内容可以显示</td>
            </tr>
    <%
        }else{
            for(int i = 0, length = votes.size(); i < length; i++){
                numAll += MyTool.strToInt(votes.get(i).getNum());
            }
            for(int i = 0, length = votes.size(); i < length; i++){
                picLen = MyTool.strToInt(votes.get(i).getNum()) * 145 / numAll;
    %>
    <tr class = "a">
        <td class = "a">
            <%= votes.get(i).getTitle() %>
        </td>
        <td class = "a">
            <img src="img/l.jpg" width="<%=picLen%>" height = "15"/>
        </td>
        <td class = "a">
            <%=votes.get(i).getNum()%>
        </td>
    </tr>
        <br/>
    <%
        }
    }
    %>
    <tr>
        <td>
            <a href = "index.jsp">
                <input type = "button" value = "返回主界面">
            </a>
        </td>
        <td>
            <a href = "vote.jsp">
                <input type = "button" value = "在线投票">
            </a>
        </td>
    </tr>
    </table>
</body>
</html>

DB.java (database operations)

package com.database;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import com.valuebean.UserSingle;
import com.valuebean.voteSingle;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class DB {
    private String className;
    private String url;
    private String username;
    private String password;
    private Connection con;
    private Statement st;
    private ResultSet res;
    public DB() {
        className="com.mysql.jdbc.Driver";
        url="jdbc:mysql://localhost:3306/votedb";
        username = "root";
        password = "3.14159";
    }
    public void loadDriver() {
        try {
            Class.forName(className);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            System.out.println("加载数据库驱动失败!");
            e.printStackTrace();
        }
    }
    public void getConnection() {
        loadDriver();
        try {
            con = (Connection) DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("连接数据库失败!");
            e.printStackTrace();
        }
    }
    public void getStatement() {
        getConnection();
        try {
            st = (Statement) con.createStatement();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("获取statement对象失败");
            e.printStackTrace();
        }
    }
    public void getResultSet(String sql) {
        if(sql != null && !sql.equals("")) {
            getStatement();
            try {
                res = st.executeQuery(sql);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                System.out.println("查询数据库失败!");
                e.printStackTrace();
            }
        }
    }
    public void closed() {
        try {
            if(res != null) {
                res.close();
            }
            if(con != null) {
                con.close();
            }
            if(st != null) {
                st.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("关闭数据库失败!");
            e.printStackTrace();
        }
    }
    public int update(String sql) {
        int i = -1;
        if(sql != null && !sql.equals("")) {
            getStatement();
            try {
                i = st.executeUpdate(sql);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                System.out.println("数据库更新失败!");
                e.printStackTrace();
            }finally {
                closed();
            }
        }
        return i;
    }
    public ArrayList<voteSingle> getVotes(){
        String sql = "select * from vote";
        getResultSet(sql);
        ArrayList<voteSingle> votes = new ArrayList<voteSingle>();
        try {
            while(res.next()) {
                voteSingle v = new voteSingle();
                v.setId(res.getString(1));
                v.setTitle(res.getString(2));
                v.setNum(res.getString(3));
                votes.add(v);
            }
            res.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return votes;
    }
    public ArrayList<UserSingle> getUsers(){
        String sql = "select * from users";
        getResultSet(sql);
        ArrayList<UserSingle> users = new ArrayList<UserSingle>();
        try {
            while(res.next()) {
                UserSingle u = new UserSingle();
                u.setId(res.getString(1));
                u.setIp(res.getString(2));
                u.setLastTime(res.getLong(3));
                users.add(u);
            }
            res.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return users;
    }
    public UserSingle findUser(String ip) {
        UserSingle u = null;
        String sql = "select * from users where ip = '" + ip + "'";
        getResultSet(sql);
        if(res != null) {
            try {
                while(res.next()) {
                    u = new UserSingle();
                    u.setId(res.getString(1));
                    u.setIp(res.getString(2));
                    u.setLastTime(res.getLong(3));
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                System.out.println("封装users表中数据失败!finduser函数");
                e.printStackTrace();
            }finally {
                closed();
            }
        }
        return u;
    }
    public voteSingle findvote(int id) {
        voteSingle u = new voteSingle();
        String sql = "select * from vote where id = " + id;
        getResultSet(sql);
        if(res == null) {
            u = null;
            return u;
        }else {
            try {
                while(res.next()) {
                    u.setId(res.getString(1));
                    u.setTitle(res.getString(2));
                    u.setNum(res.getString(3));
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return u;
        }
    }
}

UserSingle.java

package com.valuebean;

public class UserSingle {
    private String id;
    private String ip;
    private long lastTime;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getIp() {
        return ip;
    }
    public void setIp(String ip) {
        this.ip = ip;
    }
    public long getLastTime() {
        return lastTime;
    }
    public void setLastTime(long lastTime) {
        this.lastTime = lastTime;
    }
}

voteSingle.java

package com.valuebean;

public class voteSingle {
    private String id;
    private String title;
    private String num;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getNum() {
        return num;
    }
    public void setNum(String num) {
        this.num = num;
    }
}

MyTool.java

package com.toolbean;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyTool {
    public static String toChinese(String str) {
        if(str == null) {
            str="";
        }
        try {
            str = new String(str.getBytes("ISO-8859-1"),"gb2312");
        }catch(UnsupportedEncodingException e) {
            str="";
            e.printStackTrace();
        }
        return str;
    }
    public static int strToInt(String str) {
        if(str == null || str.equals("")) {
            str = "0";
        }
        int i = 0;
        try {
            i = Integer.parseInt(str);
        }catch(NumberFormatException e) {
            i = 0;
            e.printStackTrace();
        }
        return i;
    }
    public static String formatDate(long ms){
        Date date=new Date(ms);
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate=format.format(date);
        return strDate;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325636072&siteId=291194637