javaweb项目----在线投票系统总结
1.注册
-
使用Ajax进行验证注册的账户名是否已经存在,失去焦点事件
$(function(){ $("#username").blur(function(){ var username=$("#username").val(); //获取输入框的值 $.ajax({ url:"${pageContext.request.contextPath}/RegisterServlet", data:{"username":username}, type:"post", dataType: "json", success: function(data){ if(data.flag==true){ $("#msg").text("通过"); }else{ $("#msg").text("账号已经存在,请重新输入"); } }, error:function(){ alert("异步请求失败"); } }) }) });
-
传到后台servlet
String name=request.getParameter("username"); String password=request.getParameter("password"); String password1=request.getParameter("password1");
UserDao ud=new UserDao(); HttpSession session = request.getSession(false); User user = null; if (password1 == null) { user = ud.SearchUser(name);//调用dao里面的方法查看用户名是否存在 PrintWriter out = response.getWriter(); if (user != null) { user.setFlag(false);//表示用户名存在 } else { //不存在就把注册的用户名存到数据库里面,发送到页面,在页面显示该用户名可以注册 user = new User(); user.setFlag(true); user.setUsername(name); session.setAttribute("user", user); } String userStr = JSONObject.toJSONString(user); out.print(userStr); return; } //如果用户名和密码不为空,就进行注册,把它存到数据库里面 if (name != null && password1 != null) { ud.RegUser(name, password1); } request.getRequestDispatcher("registerSuccess.jsp").forward(request, response); }
-
验证密码是否一致
function sub(){ var password=$("#password").val();//获取密码的值 var password1=$("#password1").val(); if(password==""){//比较第一个密码框是否 $("#pmsg1").html("密码不能为空"); }else if(password1==""){ $("#pmsg").html("sorry,重复密码不能为空"); }else if(password!=password1){ $("#pmsg").html("密码不一致"); }else{ $("#form").submit(); } }
2.显示列表分页
private int page = 1;//第一页
private int pageSize = 5;//当前页面的大小
-
调用dao里面的方法,使用MySQL关键字limit
public List<Article> findArticle(int page,int pageSize){ Connection con=DBUtil.getConnection(); List<Article> articles=new ArrayList<Article>(); String sql="select * from article limit ?,?"; try { PreparedStatement pstm=con.prepareStatement(sql); pstm.setInt(1, (page-1)*pageSize); pstm.setInt(2, pageSize); ResultSet rs=pstm.executeQuery();
-
统计总页数
public int totalPage(int pageSize) { Connection con = DBUtil.getConnection(); String sql = "select count(*) as num from user"; PreparedStatement pstm = null; ResultSet rs = null; int num = 0; try { pstm = con.prepareStatement(sql); rs = pstm.executeQuery(); rs.next(); num = rs.getInt("num"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (num % pageSize == 0) { return num / pageSize; } else { return num / pageSize + 1; } }
-
在servlet里调用,存到session里发送到页面
int pages = ad.totalPage(pageSize); List<Article> articles = ad.findArticle(page, pageSize); session.setAttribute("page", page); session.setAttribute("pages", pages); request.getRequestDispatcher("voteList.jsp").forward(request, response);
-
页面调用
<tr> <td style="padding-left: 400px"> <c:choose> <c:when test="${page>1}"> <a href="${pageContext.request.contextPath}/IndexServlet?page=${page-1}">上一页</a> </c:when> <c:otherwise> 首页 </c:otherwise> </c:choose> ${page}/${pages} <c:choose> <c:when test="${page<pages}"> <a href="${pageContext.request.contextPath}/IndexServlet?page=${page+1}">下一页</a> </c:when> <c:otherwise> 最后一页 </c:otherwise> </c:choose> </td> </tr>
3.倒计时功能的实现
-
在数据库获取截止时间
//查询article表中的所有信息 public List<Article> findArticle(int page,int pageSize){ Connection con=DBUtil.getConnection(); List<Article> articles=new ArrayList<Article>(); String sql="select * from article limit ?,?"; try { PreparedStatement pstm=con.prepareStatement(sql); pstm.setInt(1, (page-1)*pageSize); pstm.setInt(2, pageSize); ResultSet rs=pstm.executeQuery(); while(rs.next()){ Article article=new Article(); article.setId(rs.getInt("id")); article.setTitle(rs.getString("title")); article.setType(rs.getInt("type")); article.setCreatime(rs.getTimestamp("createtime")); article.setEndtime(rs.getTimestamp("endtime"));//获取截止时间,存到Article类里面 //统计选项总数 String sql1="SELECT COUNT(*) as sum FROM optionss where articleid=?"; PreparedStatement pstm1=con.prepareStatement(sql1); pstm1.setInt(1, article.getId()); ResultSet rs1=pstm1.executeQuery(); while(rs1.next()){ article.setNum(rs1.getInt("sum")); //System.out.println("显示计数"+article.getNum()); } //统计有多少人投票 String sql_2="SELECT COUNT(DISTINCT `voterid`) AS num FROM `vote` WHERE `articleid`=?"; PreparedStatement pstm_2=con.prepareStatement(sql_2); pstm_2.setInt(1, article.getId()); ResultSet rs_2=pstm_2.executeQuery(); while(rs_2.next()){ article.setSum(rs_2.getInt("num")); //System.out.println("统计投票总人数为="+article.getSum()); } articles.add(article); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return articles; }
-
在servlet里面调用,发送到页面
List<Article> articles = ad.findArticle(page, pageSize); List<Timestamp> endTimes=new ArrayList<Timestamp>(); for(Article art :articles){ Timestamp endTime=art.getEndtime(); endTimes.add(endTime); } session.setAttribute("endTime", endTimes); request.getRequestDispatcher("voteList.jsp").forward(request, response);
-
在页面显示(因为在页面使用了foreach,所以需要在页面写Java代码显示)
<c:forEach items="${articles}" var="art" > <c:set var="cI" value="${art}" scope="request"></c:set>//方便在页面使用Java代码调用el表达式 <tr> <td width="810px"> <span class="p1"> <img src="./image/vote_icon.gif"> <a href="${pageContext.request.contextPath}/LookVote?titleId=${art.id}" id="h1">${art.title}</a> </span><br> <span class="p2"> 共有${art.num}个选项,已有${art.sum}个网友参与了投票。 </span> <% Article art = (Article)request.getAttribute("cI"); Timestamp time = art.getEndtime(); Date oDate = new Date();//获取当前日期对象 Long oldTime = oDate.getTime();//现在距离1970年的毫秒数 Date newDate = new Date(time.getTime());//获取数据库中的截止时间 Long newTime = newDate.getTime();//2020年距离1970年的毫秒数 int second = (int)Math.floor((newTime - oldTime) / 1000);//未来时间距离现在的秒数 int day=0; int hour =0; int minute = 0; if(second >=0){ day = (int)Math.floor(second / 86400);//整数部分代表的是天;一天有24*60*60=86400秒 ; second = second % 86400;//余数代表剩下的秒数; hour = (int)Math.floor(second / 3600);//整数部分代表小时;一个小时有3600秒 second %= 3600; //余数代表 剩下的秒数; minute = (int)Math.floor(second / 60);//一分钟有60秒 second %= 60; }else{ day = 0; second = second % 86400; hour = 0; second %= 3600; minute = 0; second %= 60; second=0; } %> <p class="p2"> 投票截止时间剩余: <span style="color:red"><%=day+"天"+hour+"小时"+minute+"分钟"+second+"秒" %></span> </p>
4.添加投票实现
-
在页面设置input的name的值一样
添加新投票<form action="AddServlet" method="post" οnsubmit="return check()"> <table style="width: 480px"> <tbody><tr> <td>投票内容:</td> <td><input type="text" name="title" class="bb"></td> </tr> <tr> <td>投票类型:</td> <td align="left"> <input type="radio" name="type" value="single" checked="checked">单选 <input type="radio" name="type" value="more">多选 </td> </tr> </tbody><tbody id="addTr"> <tr> <td>投票选项:</td> //投票选项的name都一样 <td><input type="text" name="option" class="bb"></td> </tr> <tr> <td></td> <td><input type="text" name="option" class="bb"></td> </tr> </tbody> <tbody> <tr> <td>截止日期:</td> <td> <input type="text" placeholder="请选择日期和时间" id="datetime" class="bb" name="endTime"> </td> </tr> <tr> <td></td>
-
传到后台servlet
- 使用getParameterValues获取多个name=option的值,用数组存起来
String[] option = request.getParameterValues("option");
-
传到dao里面,存进数据库
public void AddVote(String title,String[] option,String type,int voterId,String endTime){ Connection con=DBUtil.getConnection(); String sql="insert into article(title,type,voterid,endtime)values(?,?,?,?)"; String sql1="select id from article where title=?"; String sql2="insert into optionss(optionvalue,articleid)values(?,?)"; Article article=null; int form=0; try { PreparedStatement ps=con.prepareStatement(sql); PreparedStatement pstm_1=con.prepareStatement(sql1); PreparedStatement pstm_2=con.prepareStatement(sql2); ps.setString(1, title); if(type.equals("single")){ ps.setInt(2, form); }else if(type.equals("more")){ form=1; ps.setInt(2, form); } ps.setInt(3, voterId); ps.setString(4, endTime); ps.executeUpdate(); pstm_1.setString(1, title); ResultSet rs_1=pstm_1.executeQuery(); while(rs_1.next()){ article=new Article(); article.setId(rs_1.getInt("id")); for(int i=0;i< option.length;i++){ //System.out.println("+++++"+option[i]); pstm_2.setString(1, option[i]); pstm_2.setInt(2, article.getId()); pstm_2.executeUpdate(); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }