必威体育Betway必威体育官网
当前位置:首页 > IT技术

JSP实现在线投票系统

时间:2019-08-14 16:13:42来源:IT技术作者:seo实验室小编阅读:52次「手机版」
 

在线投票系统

系统介绍

一个网站的发展壮大靠的就是众多用户的支持,一个好的网站一定要注意与用户之间信息的交流,及时得到用户反馈信息,并及时改进,这也是一个网站持续发展的基础。也正是由于该原因,网络上各式各样的投票系统层出不穷。接下来的项目,就是来编制一个在线投票系统,该系统可以对投票数量进行累加、查询统计票数等操作。

操作注意事项

1.在进行投票操作时,一个小时内只能投一次票。

效果图显示:

这里写图片描述

这里写图片描述

这里写图片描述

代码如下:

数据库建库建表代码:

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>
    <p>
        <a href = "vote.jsp"><input type ="button" value = "在线投票"/></a>
        <br/>
        <a href = "showVote.jsp"><input type ="button" value = "投票结果"/></a>
    </p>

</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(数据库操作)

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;
    }
}

相关阅读

使用SSM实现简单工作流系统之实现篇

项目说明本项目是依据《轻量级 Java EE 企业应用实战 第4版》的最后一章中的项目实现的,原本项目使用的框架是Struts2 + Spring 4

CreateFileMapping实现的共享内存及用法

在32位的Windows系统中,每一个进程都有权访问他自己的4GB(232=4294967296)平面地址空间,没有段,没有选择符,没有near和far指针,没有near

JSP技术简介

1 JSP技术的特征 JSP技术所开发的web应用程序是基于Java的,它拥有Java跨平台的特性,以及业务代码分离,组建重用,基础Java servlet功能

线性回归 - 机器学习多元线性回归 - 一步一步详解 - P

目录 数据导入 单变量线性回归 绘制散点图 相关系数R 拆分训练集和测试集 多变量线性回归 数据检验(判断是否可以做线性回归) 训练

最新网络赚钱方法 怎么做可以实现在家赚钱?

在家里很多人都很烦恼的一个问题就是如何赚钱,现在特别多的人都不喜欢做出去,尤其是长期呆在家里久了的人以后,就会考虑这个问题了,在

分享到:

栏目导航

推荐阅读

热门阅读