使用servlet和jsp在数据库中插入5行数据

时间:2015-10-29 10:00:57

标签: java mysql jsp servlets

我想在mysql数据库中插入5行数据。我知道如何一次一行,但我不知道如何发送多行。

timesheet.jsp

<%@page language="java" contentType="text/html charset=UTF-8" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>  
    <head>  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script type="text/javascript">
    $(window).load(function(){
         function updateHours(row){ 
            var $date = row.find('[name="date"]');
            var $time1 = row.find('[name="logintime"]');
            var $time2 = row.find('[name="logouttime"]');
            var $time3 = row.find('[name="lunch"]');
            var $time4 = row.find('[name="afterlunchlogin"]');
            var $time5 = row.find('[name="afterlunchlogout"]');
            var $diff = row.find('.totalTime');
            var $over = row.find('.overTime');

                    if($time1.val() && $time2.val() && $time3.val() && $time4.val() && $time5.val())
            {   
                 var dateInput = $date.val();
                var dtStart = new Date(dateInput + " " + $time1.val());
                var dtEnd = new Date(dateInput + " " + $time2.val());
                var dtLunch= new Date(dateInput + " " + $time3.val());
                var dtStartafterlunch = new Date(dateInput + " " + $time4.val());
                var dtEndafterlunch = new Date(dateInput + " " + $time5.val());

                var diff = ((dtEnd - dtStart)+(dtEndafterlunch-dtStartafterlunch)) / 1000;

                var totalTime = 0;
                var overTime = 0;

                if (diff > 60*60*8) {

                    overTime = formatDate(diff - 60*60*8);
                } else {
                    totalTime = formatDate(diff);
                }
                totalTime = formatDate(diff);
                $diff.val(totalTime);
                $over.val(overTime);
            }
        }

        function formatDate(diff){
            var hours = parseInt( diff / 3600 ) % 24;
            var minutes = parseInt( diff / 60 ) % 60;
            var seconds = diff % 60;

            return (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds);
        }

        $(".start, .end, .lunch, .startafterlunch, .endafterlunch, .totalTime").on("change, keyup", function(){
            debugger
            updateHours($(this).closest('tr'));
        });

    });
         </script>

    <title>Timesheet Page</title>  
    </head>  
    <body>  
        <header>
            <h2>WEEKLY TIME SHEET MANAGEMENT V 1.0</h2>
        </header>

        <form action="TimeSheet" method="post">
            <fieldset style="width: 90%">  
                <legend>Timesheet</legend>   
                <h2>Time Sheet application</h2>
    <table border=1>
    <tr><th>Employee ID</th><th>Date</th><th>Time In</th><th>Time Out</th><th>Lunch</th><th>After Lunch Time in</th><th>After Lunch Time out</th><th>Task Description</th><th>Total Hours</th><th>Overtime</th> </tr>


        <tr> <td><input type="text" name="empid" required="required" /></td>   
    <td><input type="date" id="date" name="date"/></td>
    <td><input type="time" class="start" name="logintime"/></td>
    <td><input type="time" class="end"name="logouttime" /></td>
    <td><input type="time" class="lunch" name="lunch" /></td>
    <td><input type="time" class="startafterlunch" name="afterlunchlogin"/></td>
    <td><input type="time" class="endafterlunch" name="afterlunchlogout"/></td>
    <td><input type="textarea" name="task" required="required" /></td>
    <td><input class="totalTime" readonly="readonly" /></td>
    <td><input class="overTime" readonly="readonly" /></td></tr>
        <tr> <td><input type="text" name="empid" required="required" /></td>   
    <td><input type="date" id="date" name="date"/></td>
    <td><input type="time" class="start" name="logintime"/></td>
    <td><input type="time" class="end"name="logouttime" /></td>
    <td><input type="time" class="lunch" name="lunch" /></td>
    <td><input type="time" class="startafterlunch" name="afterlunchlogin"/></td>
    <td><input type="time" class="endafterlunch" name="afterlunchlogout"/></td>
    <td><input type="textarea" name="task" required="required" /></td>
    <td><input class="totalTime" readonly="readonly" /></td>
    <td><input class="overTime" readonly="readonly" /></td></tr>
        <tr> <td><input type="text" name="empid" required="required" /></td>   
    <td><input type="date" id="date" name="date"/></td>
    <td><input type="time" class="start" name="logintime"/></td>
    <td><input type="time" class="end"name="logouttime" /></td>
    <td><input type="time" class="lunch" name="lunch" /></td>
    <td><input type="time" class="startafterlunch" name="afterlunchlogin"/></td>
    <td><input type="time" class="endafterlunch" name="afterlunchlogout"/></td>
    <td><input type="textarea" name="task" required="required" /></td>
    <td><input class="totalTime" readonly="readonly" /></td>
    <td><input class="overTime" readonly="readonly" /></td></tr>
        <tr> <td><input type="text" name="empid" required="required" /></td>   
    <td><input type="date" id="date" name="date"/></td>
    <td><input type="time" class="start" name="logintime"/></td>
    <td><input type="time" class="end"name="logouttime" /></td>
    <td><input type="time" class="lunch" name="lunch" /></td>
    <td><input type="time" class="startafterlunch" name="afterlunchlogin"/></td>
    <td><input type="time" class="endafterlunch" name="afterlunchlogout"/></td>
    <td><input type="textarea" name="task" required="required" /></td>
    <td><input class="totalTime" readonly="readonly" /></td>
    <td><input class="overTime" readonly="readonly" /></td></tr>
        <tr> <td><input type="text" name="empid" required="required" /></td>   
    <td><input type="date" id="date" name="date"/></td>
    <td><input type="time" class="start" name="logintime"/></td>
    <td><input type="time" class="end"name="logouttime" /></td>
    <td><input type="time" class="lunch" name="lunch" /></td>
    <td><input type="time" class="startafterlunch" name="afterlunchlogin"/></td>
    <td><input type="time" class="endafterlunch" name="afterlunchlogout"/></td>
    <td><input type="textarea" name="task" required="required" /></td>
    <td><input class="totalTime" readonly="readonly" /></td>
    <td><input class="overTime" readonly="readonly" /></td></tr>
    </table>
            </fieldset>      
             <input type="submit" value="Submit">
        </form>
       <a href="logout.jsp">Logout</a>
    </body>  
    </html>  

在TimsheetDao.java

package com.eis.Dao;
import com.eis.bean.ConnectionProvider;
import com.eis.bean.EmployeeBean;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;

    public class TimeSheetDao {
  public static int insert(EmployeeBean eb,String sql) throws Exception {

    int i=0;  
    PreparedStatement ps=null;
    System.out.println("In TimesheetDao");
    Connection conn=ConnectionProvider.getConn();  
    try{ 


        System.out.println(" in try in Timesheetdao");

         ps = conn.prepareStatement(sql);

        ps.setString(1,eb.getEmpid());
       // ps.setDate(2, (java.sql.Date) eb.getLoginDate());
       // ps.setDate(3, (Date) eb.getLoginTime());  
       // ps.setDate(4, (Date) eb.getLogoutTime());  
        ps.setDate(2,new Date(eb.getLogindate().getTime()));
        ps.setString(3,eb.getLogintime());  
        ps.setString(4,eb.getLogouttime()); 
        ps.setString(5,eb.getLunch());
        ps.setString(6,eb.getAfterlunchlogin());  
        ps.setString(7,eb.getAfterlunchlogout()); 
        ps.setString(8,eb.getTask());
        ps.setString(9,eb.getTotal());
        ps.setString(10,eb.getOvertime());

        i=ps.executeUpdate();  
        /*rs = pst.executeQuery();  
                    status = rs.next(); */
        }
    catch(Exception e){
        System.out.println(e);
    }
    finally { 
        if (conn != null) {  
            try {  
                conn.close();  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
        }
        if (ps != null) {  
            try {  
                ps.close();  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
        }  

    }  
    return i;  

}
}

在TimeSheetServlet.java中

    package com.eis.servlet;

    import com.eis.Dao.TimeSheetDao;
    import com.eis.bean.EmployeeBean;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;

    public class TimeSheet extends HttpServlet {

        private static final long serialVersionUID = 1L;

        private TimeSheetDao dao;
        public TimeSheet() {
            super();
            dao = new TimeSheetDao();
        }

        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException, ParseException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            EmployeeBean eb = new EmployeeBean();
            String Emp_id=request.getParameter("empid");    
            eb.setEmpid(Emp_id);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
            Date logindate = new java.sql.Date(formatter.parse(request.getParameter("logindate")).getTime());
            eb.setLogindate((java.sql.Date) logindate);
            String LoginTime=request.getParameter("logintime");
            eb.setLogintime(LoginTime);
            String LogoutTime=request.getParameter("logouttime");   eb.setLogouttime(LogoutTime);
            String Lunch=request.getParameter("lunch"); eb.setLunch(Lunch);
            String AfterLunchLogin=request.getParameter("afterlunchlogin"); eb.setAfterlunchlogin(AfterLunchLogin);
            String AfterLunchLogout=request.getParameter("afterlunchlogout"); eb.setAfterlunchlogout(AfterLunchLogout);
            String TaskDescription=request.getParameter("task"); eb.setTask(TaskDescription);
            String TotalHours=request.getParameter("total");  eb.setTotal(TotalHours);
            String OverTime=request.getParameter("overtime"); eb.setOvertime(OverTime);

            System.out.println(request.getParameter("empid"));
            HttpSession session = request.getSession(true);  
            try{if (Emp_id!=null){
                session.setAttribute("Emp_id",Emp_id);}
            }catch(Exception e){e.printStackTrace();}
            try{if (logindate!=null){
                session.setAttribute("LoginDate",logindate);}
            }catch(Exception e){e.printStackTrace();}
            try{if (LoginTime!=null){
                session.setAttribute("LoginTime",LoginTime);}
            }catch(Exception e){e.printStackTrace();}
            try{if (LogoutTime!=null){
                session.setAttribute("LogoutTime",LogoutTime);}
            }catch(Exception e){e.printStackTrace();}
            try{if (Lunch!=null){
                session.setAttribute("Lunch",Lunch);}
            }catch(Exception e){e.printStackTrace();}
            try{if (AfterLunchLogin!=null){
                session.setAttribute("AfterLunchLogin",AfterLunchLogin);}
            }catch(Exception e){e.printStackTrace();}
            try{if (AfterLunchLogout!=null){
                session.setAttribute("AfterLunchLogout",AfterLunchLogout);}
            }catch(Exception e){e.printStackTrace();}
            try{if (TaskDescription!=null){
                session.setAttribute("TaskDescription",TaskDescription);}
            }catch(Exception e){e.printStackTrace();}
            try{if (TotalHours!=null){
                session.setAttribute("TotalHours",TotalHours);}
            }catch(Exception e){e.printStackTrace();}
            try{if (OverTime!=null){
                session.setAttribute("OverTime",OverTime);}
            }catch(Exception e){e.printStackTrace();}


            TimeSheetDao dao = new TimeSheetDao();
            System.out.println("before sql");
              String sql= "insert into logintable values(?,?,?,?,?,?,?,?,?,?)";
              System.out.println("after sql");
           try {
               System.out.println("in try servlet after sql");
               int status = TimeSheetDao.insert(eb, sql);

               System.out.println("in try dao after sql");
            if(status!=0){
                out.print("<p style=\"color:Green\">Record saved successfully!!</p>");  
                RequestDispatcher rd=request.getRequestDispatcher("index.jsp");    
                rd.include(request,response);
            }
           else{    
                out.print("<p style=\"color:red\">**Record cannot be saved!**</p>");    
                RequestDispatcher rd=request.getRequestDispatcher("index.jsp");    
                rd.include(request,response);
            }

             }
           catch(Exception e){
               e.printStackTrace();
           }
        }

        // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
        /**
         * Handles the HTTP <code>GET</code> method.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            try {
                processRequest(request, response);
            } catch (ParseException ex) {
                Logger.getLogger(TimeSheet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        /**
         * Handles the HTTP <code>POST</code> method.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            try {
                processRequest(request, response);
            } catch (ParseException ex) {
                Logger.getLogger(TimeSheet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        /**
         * Returns a short description of the servlet.
         *
         * @return a String containing servlet description
         */
        @Override
        public String getServletInfo() {
            return "Short description";
        }// </editor-fold>

    }

引用EmployeeBean:

package com.eis.bean;

    import java.util.Date;

    public class EmployeeBean {
        private String empid;
        private java.sql.Date logindate;
        private String logintime;
        private String logouttime;
        private String lunch;
        private String afterlunchlogin;
        private String afterlunchlogout;
        private String task;
        private String total;
        private String overtime;

        public String getEmpid() {
            return empid;
        }

        public void setEmpid(String empid) {
            this.empid = empid;
        }

        public java.sql.Date getLogindate() {
            return logindate;
        }

        public void setLogindate(java.sql.Date logindate) {
            this.logindate = logindate;
        }

        public String getLogintime() {
            return logintime;
        }

        public void setLogintime(String logintime) {
            this.logintime = logintime;
        }

        public String getLogouttime() {
            return logouttime;
        }

        public void setLogouttime(String logouttime) {
            this.logouttime = logouttime;
        }

        public String getLunch() {
            return lunch;
        }

        public void setLunch(String lunch) {
            this.lunch = lunch;
        }

        public String getAfterlunchlogin() {
            return afterlunchlogin;
        }

        public void setAfterlunchlogin(String afterlunchlogin) {
            this.afterlunchlogin = afterlunchlogin;
        }

        public String getAfterlunchlogout() {
            return afterlunchlogout;
        }

        public void setAfterlunchlogout(String afterlunchlogout) {
            this.afterlunchlogout = afterlunchlogout;
        }

        public String getTask() {
            return task;
        }

        public void setTask(String task) {
            this.task = task;
        }

        public String getTotal() {
            return total;
        }

        public void setTotal(String total) {
            this.total = total;
        }

        public String getOvertime() {
            return overtime;
        }

        public void setOvertime(String overtime) {
            this.overtime = overtime;
        }

        @Override
        public String toString() {
            return "EmployeeBean [empid=" + empid + ",logindate=" + logindate + ", logintime=" + logintime+ ", logouttime=" + logouttime + ", lunch=" + lunch+ ", afterlunchlogin=" + afterlunchlogin+ ", afterlunchlogout=" + afterlunchlogout+ ", task=" + task+ ", total=" + total+ ",overtime=" + overtime+ "]";
        }

    }

我不知道如何使employeebean列出类型... pelase检查Timesheetservlet和timesheetdao。

请帮我在数据库中插入5行。

谢谢!

2 个答案:

答案 0 :(得分:1)

您需要使用批量插入:http://viralpatel.net/blogs/batch-insert-in-java-jdbc/查看&#34; SQL注入安全批处理&#34;部分。我修改了TimeSheetDao.insert方法,如下所示:

import java.sql.Connection;
import java.sql.PreparedStatement;

public class TimeSheetDao {
  // this sql string can be static final  
  public static final String sql= "insert into logintable values(?,?,?,?,?,?,?,?,?,?)";

   public static int insert(List<EmployeeBean> employees) throws Exception {     

    Connection connection = new getConnection();
    PreparedStatement ps = connection.prepareStatement(sql);

    try {
        for (EmployeeBean employee: employees) {

            // set parameters here
            ps.setDate(2,new Date(eb.getLogindate().getTime()));
            ps.setString(3,eb.getLogintime());  
            ps.setString(4,eb.getLogouttime()); 
            ps.setString(5,eb.getLunch());
            ps.setString(6,eb.getAfterlunchlogin());  
            ps.setString(7,eb.getAfterlunchlogout()); 
            ps.setString(8,eb.getTask());
            ps.setString(9,eb.getTotal());
            ps.setString(10,eb.getOvertime());
            ps.addBatch();

        }

        ps.executeBatch();

    } finally {
        ps.close();
        connection.close();
    }         
}

答案 1 :(得分:1)

我已将您的jsp更改为具有不同行的不同名称。 并且还更改了serverlet代码以读取和构建employee bean列表。  一旦你做了这些改变,你可以使用chrisI08 abovve提到的逻辑。 timesheet.jsp。

<%@page language="java" contentType="text/html charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  

<title>Timesheet Page</title>  
</head>  
<body>  

<form action="TimeSheetServlet" method="post">
    <fieldset style="width: 90%">  
        <legend>Timesheet</legend>   
        <table> 
            <thead><tr><th>Employee ID</th><th>Date</th><th>Time In</th><th>Time Out</th><th>Lunch</th><th>After Lunch Time in</th><th>After Lunch Time out</th><th>Task Description</th><th>Total Hours</th><th>Overtime</th> </tr>
            </thead>
            <tbody>
                <tr>
                    <td><input type="text" name="empid1" required="required" /></td>   
                    <td><input type="date" id="date" name="logindate1" required="required" /></td>  
                    <td><input type="time" class="start" name="logintime1" required="required" /></td>  
                    <td><input type="time" class="end" name="logouttime1" required="required" /></td> 
                    <td><input type="time" class="lunch" name="lunch1" required="required" /></td>  
                    <td><input type="time" class="startafterlunch"  name="afterlunchlogin1" required="required" /></td>  
                    <td><input type="time" class="endafterlunch" name="afterlunchlogout1" required="required" /></td> 
                    <td><input type="textarea" name="1" required="required" /></td>
                    <td><input type="time" class="totalTime" name="total1" /></td>
                    <td><input type="time" class="overTime" name="overtime1" required="required" /></td>
                </tr>  
                <tr>
                    <td><input type="text" name="empid2" required="required" /></td>   
                    <td><input type="date" id="date" name="logindate2" required="required" /></td>  
                    <td><input type="time" class="start" name="logintime2" required="required" /></td>  
                    <td><input type="time" class="end" name="logouttime2" required="required" /></td> 
                    <td><input type="time" class="lunch" name="lunch2" required="required" /></td>  
                    <td><input type="time" class="startafterlunch"  name="afterlunchlogin2" required="required" /></td>  
                    <td><input type="time" class="endafterlunch" name="afterlunchlogout2" required="required" /></td> 
                    <td><input type="textarea" name="task2" required="required" /></td>
                    <td><input type="time" class="totalTime" name="total2" /></td>
                    <td><input type="time" class="overTime" name="overtime2" required="required" /></td>
                </tr>  
                <tr>
                    <td><input type="text" name="empid3" required="required" /></td>   
                    <td><input type="date" id="date" name="logindate3" required="required" /></td>  
                    <td><input type="time" class="start" name="logintime3" required="required" /></td>  
                    <td><input type="time" class="end" name="logouttime3" required="required" /></td> 
                    <td><input type="time" class="lunch" name="lunch3" required="required" /></td>  
                    <td><input type="time" class="startafterlunch"  name="afterlunchlogin3" required="required" /></td>  
                    <td><input type="time" class="endafterlunch" name="afterlunchlogout3" required="required" /></td> 
                    <td><input type="textarea" name="task" required="required" /></td>
                    <td><input type="time" class="totalTime" name="total3" /></td>
                    <td><input type="time" class="overTime" name="overtime3" required="required" /></td>
                </tr>  
                <tr>
                    <td><input type="text" name="empid4" required="required" /></td>   
                    <td><input type="date" id="date" name="logindate4" required="required" /></td>  
                    <td><input type="time" class="start" name="logintime4" required="required" /></td>  
                    <td><input type="time" class="end" name="logouttime4" required="required" /></td> 
                    <td><input type="time" class="lunch" name="lunch4" required="required" /></td>  
                    <td><input type="time" class="startafterlunch"  name="afterlunchlogin4" required="required" /></td>  
                    <td><input type="time" class="endafterlunch" name="afterlunchlogout4" required="required" /></td> 
                    <td><input type="textarea" name="task" required="required" /></td>
                    <td><input type="time" class="totalTime" name="total4" /></td>
                    <td><input type="time" class="overTime" name="overtime4" required="required" /></td>
                </tr>  
                <tr>
                    <td><input type="text" name="empid5" required="required" /></td>   
                    <td><input type="date" id="date" name="logindate5" required="required" /></td>  
                    <td><input type="time" class="start" name="logintime5" required="required" /></td>  
                    <td><input type="time" class="end" name="logouttime5" required="required" /></td> 
                    <td><input type="time" class="lunch" name="lunch5" required="required" /></td>  
                    <td><input type="time" class="startafterlunch"  name="afterlunchlogin5" required="required" /></td>  
                    <td><input type="time" class="endafterlunch" name="afterlunchlogout5" required="required" /></td> 
                    <td><input type="textarea" name="task5" required="required" /></td>
                    <td><input type="time" class="totalTime" name="total5" /></td>
                    <td><input type="time" class="overTime" name="overtime5" required="required" /></td>
                </tr>  
            </tbody>
        </table>  
    </fieldset>      
     <input type="submit" value="Submit">
</form>
<a href="logout.jsp">Logout</a>
</body>  
</html>  

的servlet:

List<EmployeeBean> ebList=  ArrayList<EmployeeBean>();
     SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
    for(int i=1;i<=5;i++){
        EmployeeBean eb = new EmployeeBean();
         eb.setEmpid(Emp_id);


         Date logindate = new java.sql.Date(formatter.parse(request.getParameter("logindate"+i)).getTime());
          eb.setLogindate((java.sql.Date) logindate);


      //String Date=request.getParameter("logindate");    
      String LoginTime=request.getParameter("logintime"+i);
      eb.setLogintime(LoginTime);
      eb.setLogouttime(request.getParameter("logouttime"+i));
       eb.setLunch(request.getParameter("lunch"+i));
       eb.setAfterlunchlogin(request.getParameter("afterlunchlogin"+i));
       eb.setAfterlunchlogout(request.getParameter("afterlunchlogout"+i));
       eb.setTask(request.getParameter("task"+i));
        eb.setTotal(request.getParameter("total"+i));
       eb.setOvertime(request.getParameter("overtime"+i));
    }
    TimeSheetDao.insert(ebList);

注意:我没有编译此代码。您可能需要更改一些内容。