如何在Servlet中获取所选单选按钮的值并将其存储在DB中?

时间:2019-04-17 03:55:02

标签: java mysql jsp servlets jdbc

我正在开发一种投票应用程序,可以在其中投票支持特定的选项并提交。现在,我希望将用户的选定选项放在servlet中,并将其作为投票存储在数据库中。并且,当获得新的投票时,该计数应始终增加1。但是,这没有给我想要的输出。每次我选择一个选项并单击提交时,都会像投票一样将1插入到数据库的相应列中。我已将选项命名为数据库中的列名。我希望每一次新的投票都是对先前价值的补充

以下是Voting.jsp页面:-

<div class="card" style="width: 60rem; margin-left: 45px;">
  <div class="card-body">
  Click on one of the following options to caste your vote. Then click submit.

  </div>
  </div>


<div class="card" style="width: 60rem; margin-left: 45px;">
  <div class="card-body">
  <form action="SuccessServlet" method="post">
    <label class="container">Team_1
  <input type="radio" name="radio" value="team1">
  <span class="checkmark"></span>
</label>
<label class="container">Team_2
  <input type="radio" name="radio" value="team2">
  <span class="checkmark"></span>
</label>
<label class="container">Team_3
  <input type="radio" name="radio" value="team3">
  <span class="checkmark"></span>
</label>
<label class="container">Team_4
  <input type="radio" name="radio" value="team4">
  <span class="checkmark"></span>
</label>
<button type="submit">Submit</button>
</form>
  </div>
</div>

以下是我的Servlet类:-

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



        ud.setFirst_name(request.getParameter("f1"));



        String answer = request.getParameter("radio");

        if("team1".equals(answer)) {

            System.out.println("Hello");

            writeData1();

            }

    else if ("team2".equals(answer)) {

        writeData2();

    }

    else if ("team3".equals(answer)) {

        writeData3();
    }

    else if ("team4".equals(answer)) {

        writeData4();
    }

    else {
        response.sendRedirect("Success.jsp");
    }
    response.sendRedirect("UserPage.jsp");

}



    }


      public void writeData1() {

      try {
        Class.forName("com.mysql.cj.jdbc.Driver");


      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db?autoReconnect=true&useSSL=FALSE", "root", "root");


      String query = "insert into Total_Votes(Team1) values(?)";

      PreparedStatement ps = con.prepareStatement(query);

      ps.setInt(1, 1);

      ps.executeUpdate();


      } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
        }





  }





public void writeData2() {

      try {
        Class.forName("com.mysql.cj.jdbc.Driver");


      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db?autoReconnect=true&useSSL=FALSE", "root", "root");


      String query = "insert into Total_Votes(Team2) values(?)";

      PreparedStatement ps = con.prepareStatement(query);

      ps.setInt(1, 1);

      ps.executeUpdate();


      } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
        }





  }





public void writeData3() {

      try {
        Class.forName("com.mysql.cj.jdbc.Driver");


      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db?autoReconnect=true&useSSL=FALSE", "root", "root");


      String query = "insert into Total_Votes(Team3) values(?)";

      PreparedStatement ps = con.prepareStatement(query);

      ps.setInt(1, 1);

      ps.executeUpdate();


      } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
        }





  }




public void writeData4() {

      try {
        Class.forName("com.mysql.cj.jdbc.Driver");


      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db?autoReconnect=true&useSSL=FALSE", "root", "root");


      String query = "insert into Total_Votes(Team4) values(?)";

      PreparedStatement ps = con.prepareStatement(query);

      ps.setInt(1, 1);

      ps.executeUpdate();


      } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
        }





  }

2 个答案:

答案 0 :(得分:2)

您的代码始终写1作为指定团队的总票数。如果您在需要知道总数时,在SQL中使用SUM()函数来总计一个团队的投票数,那就很好了。

还有其他两种方法可以解决此问题:

  1. 每个团队在数据库中只有一条记录。每次投票时,读取当前值(如果找不到当前值,则假定为0),对其进行递增,然后使用新值更新该记录。

    < / li>
  2. 请保持每次投票插入记录。每次投票表决时,请读取当前的MAX()值(如果找不到当前值,则假定为0),对其进行递增,并插入使用新值的另一条记录。 / p>

答案 1 :(得分:2)

假设选择了team1单选按钮,现在您需要使用team1查询来获得select的先前投票价值,如下所示:

   try {
            Class.forName("com.mysql.cj.jdbc.Driver");
          Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db?autoReconnect=true&useSSL=FALSE", "root", "root");
    String sql="select votes from Total_Votes where team=?";
                     int votes=0;
                    PreparedStatement ps = con.prepareStatement(sql);
                   ps.setString(1,"team1");//passing team1 in query
                   rs = ps.executeQuery();
                    while(rs.next())
                   {
          votes=rs.getInt("yourcoulmnname");//getting value of coulmn where votes are stored for team1
                  }
                   }catch(Exception e)
                   {
                   System.out.println(e.getMessage());
                   }

现在,使用update查询来更新投票,如下所示:

String sql1 = "UPDATE `Total_Votes` SET `yourcoulumnname`=? WHERE `team`=?";
             PreparedStatement ps = con.prepareStatement(sql1);
            int v=votes+1;//votes got from previous select query add by 1 
             ps.setInt(1,v);
             ps.setString(2,"team1");

             int i=0;
              i = ps.executeUpdate();

         if(i>0){
             System.out.println("updated");
           }

希望这对您有帮助!