Java web+MySQL编写简易候选人投票(完整代码)

Java web+MySQL编写简易候选人投票(完整代码)

代码实现效果,自己选的图片太大了,没有做更改,将就看就行
项目用到的三个jar包自己导入就行

页面效果
代码结构如下图
在这里插入图片描述

Candidate中的代码

public class Candidate {
    private int id;
    private String name;
    private String photoUrl;
    private  int votes;

    public int getId(){
        return  id;
    }
    public void setId(int id){
        this.id = id;
    }
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getPhotoUrl(){
        return photoUrl;
    }

    public void setPhotoUrl(String photoUrl){
        this.photoUrl = photoUrl;
    }
    public int getVotes(){
        return votes;
    }
    public void setVotes(int votes){
        this.votes = votes;
    }

}

AddCandidatePageServlet


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 java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/admin/addcan")
public class AddCandidatePageServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");
        PrintWriter pw = resp.getWriter();
        pw.println("<html><head><title>添加候选人</title></head>");
        pw.println("<body>");
        pw.println("<form action='add' method = 'POST' enctype='multipart/form-data'>");
        pw.println("名字: <input type='text' name='username'><br>");
        pw.println("照片:<input type='file' name = 'img'><br>");
        pw.println("<input type='submit' value = '提交'>");
        pw.println("</form>");
        pw.println("</body></html>");
    }
}

AddCandidateServlet


@WebServlet("/admin/add")
public class AddCandidateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //判断上传的文件是否以多段数据进行提交的
        if (ServletFileUpload.isMultipartContent(req)) {
            //创建FileItemFactory工厂类的示例
            FileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //创建解析数据所使用的工具类:ServletFileUpload
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            //获取文件存储的绝对路径
            String path = getServletConfig().getServletContext().getRealPath("/")+ "photos\\";
            //解析数据
            try {
                String username = null;
                String img = null;
                List<FileItem> list = servletFileUpload.parseRequest(req);
                for (FileItem fileItem : list) {
                    if (fileItem.isFormField()) {
                        username = fileItem.getString("UTF-8");
                    } else {
                        //获取图片的名字
                        img = fileItem.getName();
                        //将文件写入指定的文件夹之中
                        fileItem.write(new File(path + img));
                    }
                }
                //将文件名存入数据库

                Candidate candidate = new Candidate();
                candidate.setName(username);
                candidate.setPhotoUrl(img);
                CandidateDao candidateDao = new CandidateDao();
                candidateDao.add(candidate);
                System.out.println("存入成功");
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
        resp.sendRedirect("manage");
    }
}

DeleteCandidateServlet

@WebServlet("/admin/delete")
public class DeleteCandidateServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String id = req.getParameter("id");
        Candidate candidate=new Candidate();
        CandidateDao candidateDao=new CandidateDao();
        candidateDao.delete( Integer.parseInt(id));
        resp.sendRedirect("manage");
    }
}

ManageCandidateServlet

@WebServlet("/admin/manage")
public class ManageCandidateServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;utf-8");
//        获取数据
        CandidateDao candidateDao=new CandidateDao();
        ArrayList<Candidate> candidates= (ArrayList<Candidate>) candidateDao.candidateList();

//        获取笔
        PrintWriter pw=resp.getWriter();

//        编号
        int count=1;
        pw.print("<!DOCTYPE html><html><head> <meta charset='UTF-8'><title>管理列表</title></head><body>");
        pw.print("<div><a href='http://localhost:8080/exercise2_vote_war_exploded/admin/addcan'>添加新用户</a></div>");
        pw.print("<table border='1'>");
        pw.print("<tr><td>排名</td> <td>名字</td> <td>ID</td> <td>照片</td><td>票数</td><td>修改</td><td>删除</td></tr>");
        if (candidates!=null){
            for (Candidate person:candidates){

                pw.print("<tr>");
                pw.print("<td>"+count+"</td>");
                pw.print("<td>"+person.getName()+"</td>");
                pw.print("<td>"+person.getId()+"</td>");
                pw.print("<td><img src='http://localhost:8080/exercise2_vote_war_exploded/photos/"+person.getPhotoUrl()+"'></td>");
                pw.print("<td>"+person.getVotes()+"</td>");
                pw.print("<td><a href='http://localhost:8080/exercise2_vote_war_exploded/admin/modify?id="+person.getId()+"'>修改</a></td>");
                pw.print("<td><a href='http://localhost:8080/exercise2_vote_war_exploded/admin/delete?id="+person.getId()+"'>删除</a></td>");
                pw.print("</tr>");
                count++;
            }
        }
        pw.print("</table>");
        pw.print("<a href='http://localhost:8080/exercise2_vote_war_exploded/index'>用户列表</a>");
        pw.print("</body></html>");
    }
}

ModifyCandidatePageServlet

@WebServlet("/admin/modify")
public class ModifyCandidatePageServlet extends HttpServlet {
    //    修改候选人信息
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;utf-8");
        resp.setCharacterEncoding("utf-8");
//获取初始候选人数据
        String id1= req.getParameter("id");
        int id=Integer.parseInt(id1);
        CandidateDao candidateDao=new CandidateDao();
        Candidate candidate= candidateDao.select(id);
//        渲染成表单数据
        PrintWriter pw=resp.getWriter();
        pw.print("<!DOCTYPE html><html><head> <meta charset='UTF-8'><title>修改候选人信息</title></head><body>");
        pw.print("<form action = 'mod' method = 'POST' enctype='multipart/form-data'>");
        pw.print("id : <input type='text'  name='id' value='"+candidate.getId()+"'></br>");
        pw.print("name : <input type='text'  name='username' value='"+candidate.getName()+"'></br>");
        pw.print("photo : <input type='file' name='photo' value='"+candidate.getPhotoUrl()+"'></br>");
        pw.print("<input type='submit' value='提交'></br>");
        pw.print("</form>");
        pw.print("</body></html>");
    }
}

ModifyCandidateServlet

@WebServlet("/admin/mod")
public class ModifyCandidateServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (ServletFileUpload.isMultipartContent(req)) {
            System.out.println("qwertyy");
            //创建FileItemFactory工厂类的示例
            FileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //创建解析数据所使用的工具类:ServletFileUpload
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            //
            String path = getServletConfig().getServletContext().getRealPath("/") + "photos\\";
            //解析数据
            try {
                String username = null;
                String img = null;
                String id = null;
                List<FileItem> list = servletFileUpload.parseRequest(req);

                for (FileItem fileItem : list) {
                    System.out.println(fileItem);
                    if (fileItem.isFormField()) {
                        if ("username".equals(fileItem.getFieldName())){

                            username = fileItem.getString("UTF-8");
                            System.out.println(username+"获取用户姓名");
                        }
                        if ("id".equals(fileItem.getFieldName())){
                            System.out.println("id的获取"+fileItem.getString());
                            id = fileItem.getString("UTF-8");
                        }

                    }
                    else {
                        //获取图片的名字
                        img = fileItem.getName();
//                        id=req.getParameter("id");
                        //将文件写入指定文件夹之中
                        fileItem.write(new File(path + img));
                    }
                }
                //将文件名存入数据库
                Candidate candidate=  new Candidate();
                candidate.setName(username);
                candidate.setPhotoUrl(img);
                candidate.setId(Integer.parseInt(id));
                CandidateDao candidateDao=new CandidateDao();
                candidateDao.update(candidate);
                System.out.println("更新成功");

            } catch (Exception e) {
                e.printStackTrace();
            }
            resp.sendRedirect("manage");
        }else{
            System.out.println("错误!");
        }
    }
}

ListCandidateServlet

@WebServlet("/index")
public class ListCandidateServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //先获取数据
        CandidateDao candidateDao=new CandidateDao();
        ArrayList<Candidate> candidates= (ArrayList<Candidate>) candidateDao.candidateList();

//     排名编号 ---查询到的数据以投票数降序排序
        int count=1;
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;utf-8");
        PrintWriter printWriter=resp.getWriter();
        printWriter.print("<!DOCTYPE html><html><head> <meta charset='UTF-8'><title>简易投票系统</title></head><body>");
        printWriter.print("<table border='1'>");
        printWriter.print("<tr> <td>排名</td> <td>名字</td> <td>ID</td> <td>照片</td><td>票数</td><td>投票</td></tr>");
        if (candidates!=null){
            for (Candidate person:candidates){
                printWriter.print("<tr>");
                printWriter.println("<td>" + count + "</td>");
                printWriter.println("<td>" + person.getName() + "</td>");
                printWriter.println("<td>" + person.getId() + "</td>");
                //待修改


                printWriter.println("<td><img src='photos/" + person.getPhotoUrl() + "'></td>");
                printWriter.println("<td>" + person.getVotes() + "</td>");
                printWriter.println("<td><a href = '/exercise2_vote_war_exploded/vote?id="+ person.getId()+ "'>投票</a></td>");
                printWriter.println("</tr>");

                count++;
            }
        }

        printWriter.println("</table>");
        printWriter.println("<a href='http://localhost:8080/exercise2_vote_war_exploded/admin/manage'>管理候选人</a>");
        printWriter.println("</body></html>");
    }
}

VoteServlet

@WebServlet("/vote")
public class VoteServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        String id1=req.getParameter("id");

        if (id1!=null){
            System.out.println(id1);
            int id=Integer.parseInt(id1);
            CandidateDao candidateDao=new CandidateDao();
            candidateDao.addVote(id);
            req.getRequestDispatcher("index").forward(req,resp);
        }
        System.out.println("未获取到id");
    }
}

dao层里面的CandidateDao

public class CandidateDao implements Dao {

    Connection connection;
    {
        try{
            connection = JdbcUtil.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public void add(Candidate candidate) {
        String sql="insert into table_candidate values(null,?,?,?)";
        try(PreparedStatement ps=connection.prepareStatement(sql)){
            ps.setString(1,candidate.getName());
            ps.setString(2,candidate.getPhotoUrl());
            ps.setInt(3,candidate.getVotes());
            ps.execute();
            System.out.println("向数据库中插入一条记录");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(Candidate candidate) {
        String sql="update  table_candidate set name= ?,photoUrl = ?  where id=?";
        try(PreparedStatement ps=connection.prepareStatement(sql)){
            ps.setInt(3,candidate.getId());
            ps.setString(1,candidate.getName());
            ps.setString(2,candidate.getPhotoUrl());
//ps.setInt(3,candidate.getVotes());
            ps.execute();
            System.out.println("更新了数据库中这条id为:"+candidate.getId()+"的记录");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delete(int id) {
        String sql="delete from  table_candidate where id=?";
        try (PreparedStatement ps=connection.prepareStatement(sql);){
            ps.setInt(1,id);
            ps.execute();
            System.out.println("删除了数据库中这条id为:"+id+"的记录");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Candidate select(int id) {
        Candidate candidate=null;
        String sql=" select * from  table_candidate where id= ?";
        try(   PreparedStatement ps=connection.prepareStatement(sql);) {
            ps.setInt(1,id);

            ResultSet rs= ps.executeQuery();
            if (rs.next()){

                String name=rs.getString(2);
                String photoUrl=rs.getString(3);
                int votes=rs.getInt(4);
                candidate=new Candidate();

                candidate.setId(id);
                candidate.setName(name);
                candidate.setPhotoUrl(photoUrl);
                candidate.setVotes(votes);
                System.out.println("查询单条记录成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return candidate;
    }

    @Override
    public List<Candidate> candidateList() {
        // 直接调用有参获取候选人方法,只不过参数是0-最后
        return orderPageList(0,10000);
    }

    @Override
    public List<Candidate> orderPageList(int start, int count) {
        //        存放获取候选人列表
        ArrayList<Candidate> candidates=new ArrayList<Candidate>();
        String sql="select * from table_candidate order by votes desc limit ? , ? ";
        try (PreparedStatement ps=connection.prepareStatement(sql);)  {
            ps.setInt(1,start);
            ps.setInt(2,count);
            ResultSet rs=ps.executeQuery();
            while (rs.next()){
                Candidate candidate=new Candidate();
                int id=rs.getInt(1);
                String name=rs.getString(2);
                String photoUrl=rs.getString(3);
                int votes=rs.getInt(4);
                candidate.setId(id);
                candidate.setName(name);
                candidate.setPhotoUrl(photoUrl);
                candidate.setVotes(votes);
                candidates.add(candidate);
//                System.out.println("查询候选人信息成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return candidates;
    }
    public  void  addVote(int id){
        String sql="update  table_candidate set votes=votes+1  where id=?";
        try (  PreparedStatement ps=connection.prepareStatement(sql);){
            ps.setInt(1,id);
            ps.execute();
//            System.out.println("id为:"+id+"的候选者投票数加一");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Dao

public interface Dao {
    public void add(Candidate candidate);
    public  void update(Candidate candidate);
    public  void delete (int id);
    //获取单个候选人
    public Candidate select(int id);
    //候选人列表
    public List<Candidate> candidateList();
    //分页查询候选人
    public List<Candidate> orderPageList(int start,int count);
}

JdbcUti

public class JdbcUtil {
    private static Connection connection;
    public  static  Connection getConnection() throws ClassNotFoundException, SQLException{
        Class.forName("com.mysql.cj.jdbc.Driver");
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC", "root", "自己数据的密码");
        return connection;
    }
    //关闭连接
    public static void closeResourse(Connection connection, PreparedStatement preparedStatement){
        if(preparedStatement!=null){
            try{
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection!=null){
            try{
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void closeResourse(Connection connection, PreparedStatement preparedStatement, ResultSet rs){
        if(preparedStatement!=null){
            try{
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection !=null){
            try{
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs!=null){
            try{
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值