周末啦,最后一天,问了一下妹子,你作业写完了没有,妹子说,木有,我就傻眼了。。。
好吧,妹子,我来帮你写。
于是乎,把作业ppt下载下来,看了看,还可以,不算难,于是就帮妹子写完了这一个作业。虽然说还有一个作业ppt连我都看不懂布置的老师是想要干什么,真心想吐槽一句,老师,不给力啊。
好了,先上一个代码结构图吧:
主要代码分为java代码部分和WebContent代码部分:
java代码部分主要分成了3个包:BEAN(实体类包),DAO(数据库访问类包),Servlet(Servlet类包)
BEAN包包含了2个实体:user.java(用户实体),vote.java(参选人信息实体)
DAO包含了3个类:BaseDao.java(提供数据库连接的基本类),UserDao.java(访问用户表的DAO),VoteDao.java(访问参选人信息表的DAO)
Servlet包含了5个类:RandCode.java,YZMServlet.java(这两个类提供了验证码的功能),addVoteNumber.java(提供了投票的功能,即被选中的人票数+1),login.java(用户登录验证),reg.java(用户注册功能)
WebContent包含了4个html页面和4个JSP页面:
ShowAllVoteInfo.jsp页面:显示所有参选人的简略信息,并提供前往投票界面的通道。
addVoteNumber.jsp页面:显示被选中的那个参选人的详细信息,并提供投票功能
UserLogin.jsp页面:提供用户登录功能,并提供前往注册的通道
UserReg.jsp页面:提供新用户注册的功能。
剩下4个html页面都是简单的成功失败信息提示页面,无需过多说明。
先说一下,做这个练习的思路。我是先把实*作好了先的人。
要制作实体,先要有对应的数据库及表,
所以,第一步是创库创表加数据
create database vote go use vote go create table voteInfo ( id int primary key identity, pname varchar(20) not null, voteNumber int not null default 0, pImgSrc varchar(200) ,--图片路径 achievement1 text,--事迹 achievement2 text ) insert voteInfo values('张三',100,'1.jpg','他姓张','排行老三') insert voteInfo values('马云',111,'2.jpg','淘宝','天猫') insert voteInfo values('李连杰',33,'3.jpg','非常能打','') select * from voteInfo create table userInfo ( id int primary key identity, uaccount varchar(20) not null, upwd varchar(20) not null ) insert userInfo values('qiu','123456') insert userInfo values('yangmei','520.')
第二步,对应数据库的表制作实体:
user.java,用户实体
package BEAN; public class user { private int id; private String uaccount; private String upwd; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUaccount() { return uaccount; } public void setUaccount(String uaccount) { this.uaccount = uaccount; } public String getUpwd() { return upwd; } public void setUpwd(String upwd) { this.upwd = upwd; } }
vote.java,参选人信息实体
package BEAN; public class vote { private int id; private String pname; private int voteNumber; private String pImgSrc; private String achievement1; private String achievement2; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public int getVoteNumber() { return voteNumber; } public void setVoteNumber(int voteNumber) { this.voteNumber = voteNumber; } public String getpImgSrc() { return pImgSrc; } public void setpImgSrc(String pImgSrc) { this.pImgSrc = pImgSrc; } public String getAchievement1() { return achievement1; } public void setAchievement1(String achievement1) { this.achievement1 = achievement1; } public String getAchievement2() { return achievement2; } public void setAchievement2(String achievement2) { this.achievement2 = achievement2; } }
第三步,查看信息,列出所有需要提供的功能,并为功能编写DAO
BaseDao.java,数据库连接Dao
package DAO; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class BaseDao { private static String username = "sa"; private static String password = "123456"; private static String url = "jdbc:sqlserver://localhost:1433;databaseName=vote"; private static String classname = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; private static Connection conn; PreparedStatement stat; static{ try { Class.forName(classname); System.out.print("forName"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getCon() { try { conn = DriverManager.getConnection(url, username, password); System.out.print("getConnection"); } catch (SQLException e) { e.printStackTrace(); } return conn; } public static void closeAll(Connection conn,PreparedStatement ps,ResultSet rs){ try { if(rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { if(ps != null) ps.close(); } catch (SQLException e) { e.printStackTrace(); } try { if(conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
UserDao.java ,用户Dao
package DAO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import BEAN.user; import BEAN.vote; public class UserDao {
//提供根据实体类对象来判断是否登录成功的方法 public Boolean login(user u) throws SQLException{ Connection conn = BaseDao.getCon(); PreparedStatement statement =null; ResultSet rest = null; try { String sql = "select * from userInfo where uaccount='"+u.getUaccount() +"' and upwd='"+u.getUpwd()+"'"; statement = conn.prepareStatement(sql); rest = statement.executeQuery(); if (rest.next()) { return true; } else return false; } catch (Exception e) { e.printStackTrace(); }finally{ conn.close(); } return false; }
//判断用户注册的账号是否已经存在 public Boolean hasUser(String uaccount) throws SQLException{ Connection conn = BaseDao.getCon(); PreparedStatement statement =null; ResultSet rest = null; try { String sql = "select * from userInfo where uaccount='"+uaccount+"'"; statement = conn.prepareStatement(sql); rest = statement.executeQuery(); if (rest.next()) { return true; } else return false; } catch (Exception e) { e.printStackTrace(); }finally{ conn.close(); } return false; } //添加用户 public boolean addUser(user u) { Boolean result=false; Connection conn = BaseDao.getCon(); PreparedStatement statement =null; String sql = "insert userInfo values(?,?);"; try { statement = conn.prepareStatement(sql); statement.setString(1, u.getUaccount()); statement.setString(2, u.getUpwd()); int rows=statement.executeUpdate(); if(rows>0) result=true; else result=false; } catch (Exception e) { e.printStackTrace(); }finally{ BaseDao.closeAll(conn, statement, null); } return result; } }
VoteDao.java,参选人信息Dao
package DAO; import java.sql.*; import java.util.*; import BEAN.vote; public class VoteDao {
//得到一个List集合,该集合包含所有参选人的信息 public List<vote> selectAll() throws SQLException{ List<vote> list = new ArrayList<vote>(); Connection conn = BaseDao.getCon(); vote voteInfo = null; PreparedStatement statement =null; ResultSet rest = null; try { String sql = "select * from voteInfo"; statement = conn.prepareStatement(sql); rest = statement.executeQuery(); while (rest.next()) { voteInfo = new vote(); voteInfo.setId(rest.getInt("id")); voteInfo.setPname(rest.getString("pname")); voteInfo.setVoteNumber(rest.getInt("voteNumber")); voteInfo.setpImgSrc(rest.getString("pImgSrc")); voteInfo.setAchievement1(rest.getString("achievement1")); voteInfo.setAchievement2(rest.getString("achievement2")); list.add(voteInfo); } } catch (Exception e) { e.printStackTrace(); }finally{ conn.close(); } return list; } //为特定编号的参选人选票+1 public boolean addVoteNumber(String id) { Boolean result=false; Connection conn = BaseDao.getCon(); PreparedStatement statement =null; String sql = "update voteInfo set voteNumber=voteNumber+1 where id="+id; try { statement = conn.prepareStatement(sql); int rows=statement.executeUpdate(); if(rows>0) result=true; else result=false; } catch (Exception e) { e.printStackTrace(); }finally{ BaseDao.closeAll(conn, statement, null); } return result; } }
第四步,编写JSP页面,JSP页面相对来说要简单许多,因为在ppt里有提供,依葫芦画瓢就好啦。
ShowAllVoteInfo.jsp页面:显示所有参选人的简略信息,并提供前往投票界面的通道。
效果图:
代码部分如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="DAO.VoteDao" %> <%@ page import="BEAN.vote" %> <%@ page import="java.util.*" %> <!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>Insert title here</title> </head> <body> <% VoteDao dao=new VoteDao(); List<vote> voteInfo=dao.selectAll(); %> <table width="100%" height="768"> <% //for(int i=0;i<voteInfo.size()/3+1;i++) for(int i=0;i<voteInfo.size();i++) { vote v=voteInfo.get(i); if(i%3==0) { %> <tr> <td><img src="/vote/<%=v.getpImgSrc()%>" width=250 height=350><br><%=v.getPname() %>(<%=v.getVoteNumber() %>)票<br> <a href="/vote/addVoteNumber.jsp?id=<%=v.getId() %>" >我要投票</a></td> <%} else if(i%3<2){%> <td><img src="/vote/<%=v.getpImgSrc()%>" width=250 height=350><br><%=v.getPname() %>(<%=v.getVoteNumber() %>)票<br> <a href="/vote/addVoteNumber.jsp?id=<%=v.getId() %>" >我要投票</a></td> <%} else{%> <td><img src="/vote/<%=v.getpImgSrc()%>" width=250 height=350 ><br><%=v.getPname() %>(<%=v.getVoteNumber() %>)票<br> <a href="/vote/addVoteNumber.jsp?id=<%=v.getId() %>" >我要投票</a></td> </tr> <%} %> <%} %> </table> </body> </html>
addVoteNumber.jsp页面:显示被选中的那个参选人的详细信息,并提供投票功能
效果图:
代码部分如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="DAO.VoteDao" %> <%@ page import="BEAN.vote" %> <%@ page import="java.util.*" %> <!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=ISO-8859-1"> <title>Insert title here</title> </head> <body> <% VoteDao dao=new VoteDao(); List<vote> voteInfo=dao.selectAll(); String str=request.getParameter("id"); //for(int i=0;i<voteInfo.size()/3+1;i++) for(int i=0;i<voteInfo.size();i++) { vote v=voteInfo.get(i); if(str.equals(v.getId()+"")) { %> <img src="/vote/<%=v.getpImgSrc()%>" width=250 height=350> <br><%=v.getPname() %>(<%=v.getVoteNumber() %>)票 <br><br>主要事迹:<br>1.<%=v.getAchievement1() %><br>2.<%=v.getAchievement2() %><br><br> <% } } %> <form action="addVoteNumber" method="post"> <input type=hidden name=id value=<%=str %> /> <input type=submit value="我要投票" /> <a href="ShowAllVoteInfo.jsp">返回首页</a> </form> </body> </html>
UserLogin.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>Insert title here</title> </head> <body> <h1 >用户登录</h1> <form action="login" method=post name=frm> 账号:<input type=text name=account /><br> 密码:<input type=password name=pwd /><br> 验证码:<input type="text" name='myYZM'><img src="yzm" onclick="this.src='yzm?parm='+new Date()"><br> <input type=submit value="登录" /> <a href="UserReg.jsp">新用户注册</a> </form> </body> </html>
UserReg.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>Insert title here</title> </head> <body> <h1>新用户注册</h1> <form action="reg" method=post name=frm onsubmit="return checkData()"> 账号:<input type=text name=account /><br> 密码:<input type=password name=pwd /><br> 密码:<input type=password name=pwd2 /><br> 验证码:<input type="text" name='myYZM'><img src="yzm" onclick="this.src='yzm?parm='+new Date()"><br> <input type=submit value="注册" /> </form> <script type="text/javascript"> function checkData(){ if(frm.account.value==""){ alert("用户名不能为空!"); return false; } if(frm.pwd.value==""){ alert("密码不能为空!"); return false; } if(frm.pwd.value!=frm.pwd2.value){ alert("两次密码不一致!"); return false; } return true; } </script> </body> </html>
最后一步,为特定的功能制作servlet:
其实,一开始我看到验证码的时候我是很蛋疼的,但是妹子直接发给了我功能代码,因为我拿来主义,研究一下,使用了一下,duang,duang,duang,验证码功能就好了
哈哈,就是搞笑一下,其实验证码的功能还挺麻烦的,首先你的有两个文件:
RandCode.java,YZMServlet.java(这两个类提供了验证码的功能)
当添加了这两个类以后,需要在JSP页面和功能servlet页面添加对应的代码,才能正确实现验证。
RandCode.java文件代码作用是设置会产生的字符范围,并且产生4位的随机文字,如下:
package Servlet; import java.util.Random; public class RandCode { String code=""; public RandCode(){ Random rand = new Random(); String tmp = "@ABCDPghijkmnopqyz0123rsEFKLMNQRSTUVWXYZabcdeGHIJftuvwx456789"; code=""; for(int i=0; i<4; i++){ int index = rand.nextInt(tmp.length()); code+=tmp.substring(index, index+1); } } public String getCode() { return code; } }
YZMServlet.java文件,提供了servlet功能来产生一个验证码图片,代码部分如下:
package Servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; 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; @WebServlet("/yzm") public class YZMServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RandCode yzm = new RandCode(); BufferedImage bi = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB); Graphics g = bi.getGraphics(); g.setColor(new Color(120,200,50)); g.setFont(new Font("Tw Cen MT",Font.ROMAN_BASELINE, 24)); g.fillRect(0, 0, 80, 30); g.setColor(Color.RED); g.drawLine(20, 15, 80, 0); g.setColor(Color.PINK); g.fillRoundRect(50, 20, 5, 10, 15, 20); //设置随机验证码字符串 g.setColor(Color.blue); g.drawString(yzm.getCode(), 0, 20); //将验证码保存在session对象中 request.getSession().setAttribute("yzm", yzm.getCode()); //将生成的图片以jpg格式发送到客户端 ImageIO.write(bi, "JPG", response.getOutputStream()); } }
addVoteNumber.java文件(提供了投票的功能,即被选中的人票数+1),这是一个servlet文件,代码如下:
package Servlet; import java.io.IOException; import java.io.PrintWriter; 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 DAO.VoteDao; /** * 实现为某一个参选者投票的功能 */ @WebServlet("/addVoteNumber") public class addVoteNumber extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public addVoteNumber() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter();//得到打印对象 String str=request.getParameter("id"); VoteDao dao=new VoteDao(); Boolean result = dao.addVoteNumber(str); if(result==true) {//投票成功 String js= "<script>location.href='succ.html';</script>"; out.print(js); } else {//投票失败 String js= "<script>location.href='fail.html';</script>"; out.print(js); } } }
login.java(用户登录验证),这是一个servlet文件,代码如下:
package Servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; 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 BEAN.user; import DAO.UserDao; /** * Servlet implementation class login */ @WebServlet("/login") public class login extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public login() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter();//得到打印对象 String innerYzm = (String) request.getSession().getAttribute("yzm");//得到服务器端验证码 String userYzm = request.getParameter("myYZM");//得到用户填写的验证码 if (innerYzm.equals(userYzm)) { String uaccount=request.getParameter("account"); String upwd=request.getParameter("pwd"); UserDao dao=new UserDao(); user u=new user(); u.setUaccount(uaccount); u.setUpwd(upwd); try { if(dao.login(u))//查询数据里是否有一致的账号密码,有则登录成功,没有则失败 { String js= "<script>location.href='UserSucc.html';</script>"; out.print(js); } else {//插入失败 String js= "<script>location.href='UserFail.html';</script>"; out.print(js); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { String js = "<script>alert('登录失败,验证码出错!');location.href='UserLogin.jsp';</script>"; out.print(js); } } }
reg.java(用户注册功能),提供新用户注册功能的servlet,代码如下:
package Servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; 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 BEAN.user; import DAO.UserDao; /** * Servlet implementation class reg */ @WebServlet("/reg") public class reg extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public reg() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter();//得到打印对象 String innerYzm = (String) request.getSession().getAttribute("yzm"); String userYzm = request.getParameter("myYZM"); if (innerYzm.equals(userYzm)) { String uaccount=request.getParameter("account"); String upwd=request.getParameter("pwd"); UserDao dao=new UserDao(); user u=new user(); u.setUaccount(uaccount); u.setUpwd(upwd); try { if(dao.hasUser(uaccount)) { String js= "<script>location.href='UserFail.html';</script>"; out.print(js); return; } if(dao.addUser(u)) { String js= "<script>location.href='UserSucc.html';</script>"; out.print(js); } else {//插入失败 String js= "<script>location.href='UserFail.html';</script>"; out.print(js); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { String js = "<script>alert('登录失败,验证码出错!');location.href='UserReg.jsp';</script>"; out.print(js); } } }
在制作整个练习的时候,遇到过一些问题。也抓了不少头发,但是终究还是给我做出来了,来,为自己喝彩。。。
1.需要显示的图片不要使用中文名的图片文件,会找不到图片文件的
2.在JSP页面中导入包使用的是<% page命令,示例:<%@ page import="java.util.*" %>
3.在JSP页面中如果写普通的服务器代码可以使用<%%>将它们括起来。
4.借鉴代码的时候一点都不要改,要不然就请理解透彻,要不然就是bug地狱。
5.其实java真的比oc好太多。。。