JavaWeb投票系统

目的

帮她完成JavaWeb课程设计,也做为练手的小项目;

功能

1、可以实现在个人登陆,在线投票,票数统计的功能;
2、规定每个投票者每天只能投一票,并要求登录成功后才可以投票;
####分块
1、Login类:实现登录
2、Vote类:实现投票
3、Vote_Filter类:过滤器类,控制登录和刷票
4、UserService类:Service类用来调用UserDao操作数据库
5、UserDao类:操作数据库类
6、Voter类:投票者模型类
7、User类: 被投者模型类
8、DBUtils类:Jdbc连接MySQL工具类

数据库(表)

投票者信息表
字段 数据类型 说明
id int 序号,主键
username varchar 用户名
password varchar 密码
record varchar 最后一天投票时间
被投者信息表
字段 数据类型 说明
id int 序号,主键
name varchar 用户名
count int 票数

Login类

package cn.sy.servlet;
import java.io.IOException;
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 cn.sy.domain.Voter;
import cn.sy.service.UserService;

@WebServlet(name = "LoginServlet", urlPatterns = { "/login" })
public class Login extends HttpServlet {

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1、得到登录名和密码
		String username = request.getParameter("username");// 得到用户输入的登录名
		String password = request.getParameter("password");// 得到用户输入的密码

		// 2、将信息封装
		Voter voter = new Voter();

		voter.setUsername(username);
		voter.setPassword(password);

		
		UserService service = new UserService();

		try {
			Voter existVoter = service.login(voter);// 3、调用service中登录方法
			if (existVoter == null) {// 代表用户名或密码错误,存储错误信息在request域中,请求转发到login.jsp
				request.setAttribute("message", "登录失败:用户名或密码错误!");
				// 登录失败,请求转发到登录页面显示错误信息message
				request.getRequestDispatcher("/login.jsp").forward(request,
						response);
				return;
			} else {// 登录成功
					// 存到session里
				request.getSession().setAttribute("user",
						existVoter.getUsername());
				// 重定向到成功页面
				response.sendRedirect(request.getContextPath() + "/success.jsp");
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

login.jsp登录页面

<%@ page language="java" import="java.util.*" %>
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>


  
    
	
    
    
    
    
    登录
    
    
    
    
  
  
  
  	

sy的投票系统

JavaWeb投票系统_第1张图片

success.jsp登录成功页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>


  
    登录成功!
    
    
    
    
    
    
    
    
    
    
  
  
  	 

${user}

欢迎${user}来投票

点击投票

sy的投票系统

JavaWeb投票系统_第2张图片

Vote类

package cn.sy.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

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 cn.sy.domain.User;
import cn.sy.service.UserService;

@WebServlet(name = "VoteServlet", urlPatterns = { "/vote" })
public class Vote extends HttpServlet {

	Date currentTime;
	SimpleDateFormat formatter;
	String dateString = null;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		User exsitUser = new User();
		String name = request.getParameter("username");
		// System.out.println(name);
		User user = new User();
		user.setName(name);

		UserService service = new UserService();
		currentTime = new Date();
		formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化当前时间
		dateString = formatter.format(currentTime);// 转成字符串
		//从session域中得到当前投票者
		String username = (String) request.getSession().getAttribute("user");
		//System.out.println(username);
		try {
			//调用修改记录方法,修改数据库最后投票时间
			service.changeRecord(username,dateString);
		} catch (SQLException e2) {
			e2.printStackTrace();
		}
		// 调用Service中的查询方法
		try {
			//查询当前票数
			exsitUser = service.findCount(user);
			// System.out.println(exsitUser.getCount());
		} catch (SQLException e) {
			e.printStackTrace();
		}

		if (exsitUser != null && name.equals("zhaoliu")) {
			
			int count = exsitUser.getCount();// 得到被投人当前票数
			count += 1;// 票数加1
			try {
				service.addCount(name, count);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.setAttribute("count", "投票成功:" + name + "当前票数为" + count);
			//投票成功请求转发到投票页面显示投票成功信息
			request.getRequestDispatcher("/vote.jsp")
					.forward(request, response);
			return;
		} else if (exsitUser != null && name.equals("wangwu")) {
			
			int count = exsitUser.getCount();// 得到被投人当前票数
			count += 1;// 票数加1
			try {
				service.addCount(name, count);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.setAttribute("count", "投票成功:" + name + "当前票数为" + count);
			request.getRequestDispatcher("/vote.jsp")
					.forward(request, response);
			return;
		} else {
			request.setAttribute("message", "请选中你要投的人!");
			request.getRequestDispatcher("/vote.jsp")
					.forward(request, response);
			return;
		}

	}

}

vote.jsp投票页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>









投票






	
	

sy的投票系统

JavaWeb投票系统_第3张图片

Vote_Filter类

package cn.sy.filter;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.sy.service.UserService;
import cn.sy.domain.Voter;

@WebFilter(filterName = "VoteFilter", urlPatterns = { "/*" })
public class Vote_Filter implements Filter {
	Date currentTime;
	SimpleDateFormat formatter;
	String dateString = null;

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		// 1.强制转换
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;

		// 2.操作

		// 判断当前资源是否需要权限控制.
		String uri = request.getRequestURI();
		String contextPath = request.getContextPath();
		String path = uri.substring(contextPath.length());

		if (path.equals("/vote") || path.equals("/success")) {
			String recordTime = null;
			// 判断用户是否登录了.
			String voter = (String) request.getSession().getAttribute("user");
			UserService service = new UserService();
			if (voter == null) {
				request.setAttribute("message", "对不起,你还没用登录,请先登录!");
				request.getRequestDispatcher("/login.jsp").forward(request,
						response);
			}
			try {				// 调用查看当前数据库记录的投票者最后一次投票时间
				Voter voter2 = service.findRecord(voter);
				recordTime = voter2.getRecord();// 得到时间

				currentTime = new Date();
				formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化当前时间
				dateString = formatter.format(currentTime);// 将服务器当前时间转成字符串

				try {
					Date one = formatter.parse(dateString);
					
					Date two = formatter.parse(recordTime);
					long time1 = one.getTime();
					long time2 = two.getTime();
					long c = time1 - time2;
					if(c<24*60*60){
						request.setAttribute("message", "对不起,您已经投过票了,明天再来吧!");
						request.getRequestDispatcher("/vote.jsp").forward(request,
								response);
					}
					//System.out.println(c);
				} catch (ParseException e1) {
					//e1.printStackTrace();
					System.out.println(voter+"想重复投票!");
				}
				// System.out.println("最后一次投票时间为:"+recordTime);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
		}
		// 3.放行
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}

UserService类

package cn.sy.service;

import java.sql.SQLException;

import cn.sy.dao.UserDao;
import cn.sy.domain.User;
import cn.sy.domain.Voter;

public class UserService {

	public Voter login(Voter voter) throws SQLException {
		
		return new UserDao().login(voter);
	}

	public User findCount(User user) throws SQLException {
		return new UserDao().findCount(user);
	}

	public void addCount(String name,int count) throws SQLException {
		new UserDao().addCount(name,count);
	}

	public void changeRecord(String username, String dateString) throws SQLException {
		new UserDao().changeRecord(username, dateString);
	}

	public Voter findRecord(String voter) throws SQLException {
		return new UserDao().findRecord(voter);
	}

}

UserDao类

package cn.sy.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import cn.sy.domain.User;
import cn.sy.domain.Voter;
import cn.sy.utils.DBUtils;

public class UserDao {

	// 登录
	public Voter login(Voter voter) throws SQLException {

		String sql = "select * from voter_info where username=? and password=?";
		// 使用c3p0数据库连接池,使用封装好的DBUtils获取数据库连接
		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
		// BeanHandler(User.class)将结果集中的第一行数据封装到一个对应的JavaBean实例中
		// 执行上面写好的sql语句
		return runner.query(sql, new BeanHandler(Voter.class),
				voter.getUsername(), voter.getPassword());

	}

	public User findCount(User user) throws SQLException {

		String sql = "select count from person_info where name=?";
		// 使用c3p0数据库连接池,使用封装好的DBUtils获取数据库连接
		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
		// BeanHandler(User.class)将结果集中的第一行数据封装到一个对应的JavaBean实例中
		// 执行上面写好的sql语句
		return runner.query(sql, new BeanHandler(User.class),
				user.getName());
	}

	public void addCount(String name, int count) throws SQLException {

		String sql = "update person_info set count=" + count + " where name=?";
		// 使用c3p0数据库连接池,使用封装好的DBUtils获取数据库连接
		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
		// BeanHandler(User.class)将结果集中的第一行数据封装到一个对应的JavaBean实例中
		// 执行上面写好的sql语句
		runner.update(sql, name);
	}

	public void changeRecord(String username, String dateString)
			throws SQLException {
		String sql = "update voter_info set record=? where username=?";
		// 使用c3p0数据库连接池,使用封装好的DBUtils获取数据库连接
		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
		// BeanHandler(User.class)将结果集中的第一行数据封装到一个对应的JavaBean实例中
		// 执行上面写好的sql语句
		runner.update(sql, dateString,username);
	}
	public Voter findRecord(String voter) throws SQLException {
		
		String sql = "select * from voter_info where username=?";
		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
		
		return runner.query(sql, new BeanHandler(Voter.class), voter);
	}
}

效果图

JavaWeb投票系统_第4张图片

JavaWeb投票系统_第5张图片

JavaWeb投票系统_第6张图片

注意

欢迎加入Information Technology QQ群:567346857
JavaWeb投票系统_第7张图片

你可能感兴趣的:(Java-EE)