connection.commit仅在jsp中插入最后一行

时间:2018-08-07 08:10:21

标签: java mysql servlets jdbc

我有一个JSP,我从中调用servlet来读取excel文档,并通过逐个读取excel单元将数据插入到MySQL数据库中。当我用数据上传excel时,仅插入excel文档的最后一行。我也有提交和回滚。即使调试时一切正常。没有引发任何错误。直到提交,但只插入了最后一行。

public class AddUser extends HttpServlet {

    // location to store file uploaded
    private static final String UPLOAD_DIRECTORY = "user";

    Connection connection = null;
    Statement statement = null;
    String file_error = "";
    String message_failure = "message_failure_user";
    String message_success = "message_success_user";
    String message_failure_bulk = "message_failure_bulk";
    String message_success_bulk = "message_success_bulk";
    String message_success1 = "message_success1";
    String db_error = "Database error has occurred.";
    String success = "Added the user successfully.";
    String user_type, first_name, last_name, user_number, email_id, user_status, login_id, group_name, submit_value;
    String sms_url, SenderID, mail_user,/* mail_password,*/ password_path, playstore_link, webapp_link;
    List<String> type, names, numbers, email_ids, passwords, login_ids, group_names;
    IST ist;
    AESCrypt aESCrypt;

    public void connectToServer() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException, IOException {

        Properties properties = new Properties();
        Thread currentThread = Thread.currentThread();
        ClassLoader contextClassLoader = currentThread.getContextClassLoader();
        InputStream propertiesStream = contextClassLoader.getResourceAsStream("config.properties");
        properties.load(propertiesStream);
        String url = properties.getProperty("jdbc.url");
        String driver = properties.getProperty("jdbc.driver");
        String username = properties.getProperty("jdbc.username");
        String password = properties.getProperty("jdbc.password");
        sms_url = properties.getProperty("jdbc.sms_url");
        SenderID = properties.getProperty("jdbc.sms_senderid");
        mail_user = properties.getProperty("jdbc.sender_mailid");
        //  mail_password = properties.getProperty("jdbc.sender_mailpass");
        password_path = properties.getProperty("jdbc.password_path");
        playstore_link = properties.getProperty("jdbc.playstore_link");
        webapp_link = properties.getProperty("jdbc.webapp_link");

        Class.forName(driver).newInstance();
        connection = DriverManager.getConnection(url, username, password);
        statement = connection.createStatement();
        connection.setAutoCommit(false);
        ist = new IST();
        aESCrypt = new AESCrypt();
    }

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

        String fileName = "";

        if (!ServletFileUpload.isMultipartContent((HttpServletRequest) request)) {
            PrintWriter writer = response.getWriter();
            writer.println("Error: Form must has enctype=multipart/form-data.");
            writer.flush();
            return;
        }

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload((FileItemFactory) factory);

        String uploadPath = String.valueOf(this.getServletContext().getRealPath("")) + File.separator + UPLOAD_DIRECTORY;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        File storeFile = null;

        try {
            List<FileItem> formItems = upload.parseRequest(request);
            String ext = null;
            if (formItems != null && formItems.size() > 0) {
                for (FileItem item : formItems) {
                    if (item.isFormField()) {
                        if ("submituser".equals(item.getFieldName())) {
                            submit_value = item.getString().trim();
                        } else if ("user_type".equals(item.getFieldName())) {
                            user_type = item.getString().trim();
                        } else if ("first_name".equals(item.getFieldName())) {
                            first_name = item.getString().trim();
                        } else if ("last_name".equals(item.getFieldName())) {
                            last_name = item.getString().trim();
                        } else if ("user_number".equals(item.getFieldName())) {
                            user_number = item.getString().trim();
                        } else if ("email_id".equals(item.getFieldName())) {
                            email_id = item.getString().trim();
                        } else if ("user_status".equals(item.getFieldName())) {
                            user_status = item.getString().trim();
                        } else if ("login_id".equals(item.getFieldName())) {
                            login_id = item.getString().trim();
                        }
                    } else {
                        fileName = new File(item.getName()).getName();
                        ext = FilenameUtils.getExtension(fileName);
                        String randomFileName = UUID.randomUUID().toString();
                        fileName = randomFileName + "." + ext;

                        String filePath = String.valueOf(uploadPath) + File.separator + fileName;
                        storeFile = new File(filePath);
                        item.write(storeFile);
                    }
                }
            }
            if (submit_value.equals("Add")) {
                connectToServer();
                file_error = "";
                String sql_query = "SELECT * from user_account where mobile_no=" + user_number;
                ResultSet resultset_val = statement.executeQuery(sql_query);
                if (resultset_val.next()) {
                    file_error = "Mobile number entered is already in use. Please enter  a different number.";
                }
                if (email_id.length() != 0) {
                    String sql_query1 = "SELECT * from user_account where email_id='" + email_id + "'";
                    ResultSet resultset_val1 = statement.executeQuery(sql_query1);
                    if (resultset_val1.next()) {
                        file_error = file_error + "<br/>Email id entered is already in use. Please choose a different email id.";
                    }
                }

                String sql_query2 = "SELECT * from user_account where login_id='" + login_id + "'";
                ResultSet resultset_val2 = statement.executeQuery(sql_query2);
                if (resultset_val2.next()) {
                    file_error = file_error + "<br/>Login id entered is already in use. Please choose a different Login id.";
                }
                URL connectURL = new URL(password_path);
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        connectURL.openStream()));

                String inputLine;
                StringBuilder password = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    password.append(inputLine);
                }
                in.close();
                //AESCrypt aESCrypt = new AESCrypt();
                String encrypted = AESCrypt.bytesToHex(aESCrypt.encrypt(password.toString()));

                if (!file_error.equals("")) {
                    throw new Exception();
                } else {
                    statement.executeUpdate("insert into user_account(user_type_id,first_name,last_name,mobile_no,email_id,status,login_id,password,login_flag,last_gen_pw_ts,last_updated_ts)values('" + user_type + "','" + first_name + "','" + last_name + "','" + user_number + "','" + email_id + "','" + user_status + "','" + login_id + "','" + encrypted + "',0,'" + ist.getLastUpdatedts() + "','" + ist.getLastUpdatedts() + "')", java.sql.Statement.RETURN_GENERATED_KEYS);

                }
                connection.commit();
//                SendSMS1(user_type, first_name, user_number, password.toString(), login_id);
//                if (!email_id.isEmpty()) {
//                    SendMail1(user_type, first_name, email_id, password.toString(), login_id);
//                }

            } else if (submit_value.equals("Submit")) {
                file_error = "";
                String excelfile = uploadPath + File.separator + fileName;
                if (ext.equals("xls")) {
                    File inputFile = new File(excelfile);
                    readXls(inputFile);
                } else {
                    File inputFile = new File(excelfile);
                    readXlsx(inputFile);
                }
            }
        } catch (Exception ex) {
            try {
                if (submit_value.equals("Add")) {
                    HttpSession session = request.getSession(false);
                    session.setAttribute(message_success1, submit_value);
                    session.setAttribute(message_failure, file_error);

                    session.setAttribute("user_type", user_type);
                    session.setAttribute("login_id", login_id);
                    session.setAttribute("f_name", first_name);
                    session.setAttribute("l_name", last_name);
                    session.setAttribute("m_no", user_number);
                    session.setAttribute("e_id", email_id);
                    session.setAttribute("u_status", user_status);
                    response.sendRedirect("userNew.jsp");
                } else if (submit_value.equals("Submit")) {
                    HttpSession session = request.getSession(false);
                    session.setAttribute(message_success1, submit_value);
                    if(file_error.equals("")){
                        session.setAttribute(message_failure_bulk, db_error);
                    }else{
                    session.setAttribute(message_failure_bulk, file_error);
                    }
                    response.sendRedirect("userNew.jsp");
                }
                if (!connection.isClosed()) {
                    connection.rollback();
                }

            } catch (SQLException ex1) {
                HttpSession session = request.getSession(false);
                session.setAttribute(message_failure, db_error);
                response.sendRedirect("userNew.jsp");
            }
        } finally {
            FileUtils.cleanDirectory(new File(getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY));
            if (file_error.equals("")) {
                if (submit_value.equals("Add")) {
                    PrintWriter out = response.getWriter();
                    int user_limit = checkUserLimit();
                    if (user_limit == 0) {
                        out.println("<script type=\"text/javascript\">");
                        out.println("alert('" + success + ". You have exceeded the active users limit. Please upgrade the subscription.');");
                        out.println("location='userList.jsp';");
                        out.println("</script>");
                    } else {
                        HttpSession session = request.getSession(false);
                        session.setAttribute(message_success1, submit_value);
                        session.setAttribute(message_success, success);
                        response.sendRedirect("userNew.jsp");
                    }
                } else if (submit_value.equals("Submit")) {
                    PrintWriter out = response.getWriter();
                    int user_limit = checkUserLimit();
                    if (user_limit == 0) {
                        out.println("<script type=\"text/javascript\">");
                        out.println("alert('" + success + ". You have exceeded the active users limit. Please upgrade the subscription.');");
                        out.println("location='userList.jsp';");
                        out.println("</script>");
                    } else {
                        HttpSession session = request.getSession(false);
                        session.setAttribute(message_success1, submit_value);
                        session.setAttribute(message_success_bulk, success);
                        response.sendRedirect("userNew.jsp");
                    }
                }
            }
            try {
                if (!statement.isClosed()) {
                    statement.close();
                }
                if (!connection.isClosed()) {
                    connection.close();
                }
            } catch (SQLException ex) {
                HttpSession session = request.getSession(false);
                session.setAttribute(message_failure, db_error);
                response.sendRedirect("userNew.jsp");
            }
        }
    }

    public void readXlsx(File inputFile) throws FileNotFoundException, IOException, Exception {

        connectToServer();
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(inputFile));
        if (wb.getSheet("Users") == null) {
            file_error = file_error + "<br/>Sheet 'Users' not found in uploaded file.";
            throw new Exception();
        }
        XSSFSheet sheet = wb.getSheet("Users");
        Iterator<Row> rowIterator = sheet.iterator();
        getValue(rowIterator);
    }

    public void readXls(File inputFile) throws FileNotFoundException, IOException, Exception {
        connectToServer();

        HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(inputFile));
        if (wb.getSheet("Users") == null) {
            file_error = file_error + "<br/>Sheet 'Users' not found in uploaded file.";
            throw new Exception();
        }
        HSSFSheet sheet = wb.getSheet("Users");
        Iterator<Row> rowIterator = sheet.iterator();
        getValue(rowIterator);
    }

    public void getValue(Iterator<Row> rowIterator) throws FileNotFoundException, IOException, Exception,
            ClassNotFoundException, SQLException, IllegalAccessException, InstantiationException {

        List<String> inserts = new ArrayList<>();

        type = new ArrayList<>();
        names = new ArrayList<>();
        numbers = new ArrayList<>();
        email_ids = new ArrayList<>();
        passwords = new ArrayList<>();
        login_ids = new ArrayList<>();
        group_names = new ArrayList<>();
        Row row;
        Cell cell;
        int count = 1, allowed_limit = 0;
        boolean error = false;
        rowIterator.next();
        while (rowIterator.hasNext()) {
            row = rowIterator.next();
            error = false;
            count = count + 1;
            ArrayList<String> array = new ArrayList<>();

            for (int i = 0; i < 8; i++) {
                cell = row.getCell(i);

                if (cell == null) {
                    array.add("");
                    continue;
                }
                cell.setCellType(Cell.CELL_TYPE_STRING);
                switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_BOOLEAN:
                        array.add("" + cell.getBooleanCellValue());
                        System.out.println(cell.getBooleanCellValue());
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.println(cell.getNumericCellValue());
                        array.add("" + cell.getNumericCellValue());
                        break;
                    case Cell.CELL_TYPE_STRING:
                        System.out.println(cell.getStringCellValue().trim());
                        array.add(cell.getStringCellValue());
                        break;
                    case Cell.CELL_TYPE_BLANK:
                        array.add("" + cell.getStringCellValue());
                        break;
                }
            }

            if (array.get(0).equals("") && array.get(1).equals("") && array.get(2).equals("") && array.get(3).equals("") && array.get(4).equals("") && array.get(5).equals("") && array.get(6).equals("") && array.get(7).equals("")) {
                break;
            } else {
                String status_check = array.get(6).trim();
                if (status_check.equals("Active")) {
                    allowed_limit = allowed_limit + 1;
                }
            }
            if (!getUserLimit().equals("")) {
                int getUserLimits = Integer.parseInt(getUserLimit());
                if (allowed_limit > getUserLimits) {
                    file_error = "<br/>You have exceeded the active users limit. Please upgrade the subscription.";
                    throw new Exception();
                }
            }

            user_type = array.get(0).trim();
            login_id = array.get(1).trim();
            first_name = array.get(2).trim();
            last_name = array.get(3).trim();
            user_number = array.get(4).trim();
            email_id = array.get(5).trim();
            user_status = array.get(6).trim();
            group_name = array.get(7).trim();

            if (numbers.contains(user_number)) {
                file_error = file_error + "<br/>XLS Row No." + count + ": Duplicate mobile number found.";
                error = true;
            }
            if (email_ids.contains(email_id)) {
                file_error = file_error + "<br/>XLS Row No." + count + ": Duplicate Email Id found.";
                error = true;
            }

            if (login_ids.contains(login_id)) {
                file_error = file_error + "<br/>XLS Row No." + count + ": Duplicate Login Id found.";
                error = true;
            }
            names.add(first_name);
            numbers.add(user_number);
            if (!group_name.equals("")) {
                group_names.add(group_name);
            }
            if (!email_id.equals("")) {
                email_ids.add(email_id);
            }
            login_ids.add(login_id);

            String exp1 = "^[a-z|A-Z|]+[a-z|A-Z|0-9]*";
            if (login_id.equals("") || login_id.length() < 3) {
                file_error = file_error + "<br/>XLS Row No." + count + ": Please provide a Login ID with minimum 3 characters";
                error = true;
            }
            if (!login_id.isEmpty()) {
                if (login_id.length() > 30) {
                    file_error = file_error + "<br/>XLS Row No." + count + ": Please provide a Login ID within 30 characters.";
                    error = true;
                } else if (!login_id.matches(exp1)) {
                    file_error = file_error + "<br/>XLS Row No." + count + ": Please provide a Login ID with first letter alphabet";
                    error = true;

                } else {
                    ResultSet resultSet1 = statement.executeQuery("select user_id from user_account where login_id='" + login_id + "'");
                    if (resultSet1.next()) {
                        file_error = file_error + "<br/>XLS Row No." + count + ": Login id entered is already in use. Please choose a different Login id.";
                        error = true;
                    }
                }
            }

            if (user_type.equals("")) {
                file_error = file_error + "<br/>XLS Row No." + count + ": Please enter a valid user type.";
                error = true;
            }

            String name_reg = "[A-Za-z ]*";
            if (first_name.equals("") || first_name.length() < 3) {
                file_error = file_error + "<br/>XLS Row No." + count + ": Please enter a first name with minimum three characters length.";
                error = true;
            } else if (first_name.length() > 30) {
                file_error = file_error + "<br/>XLS Row No." + count + ": Please provide first name with length less than 30 characters.";
                error = true;
            } else if (!first_name.matches(name_reg)) {
                file_error = file_error + "<br/>XLS Row No." + count + ": First name contain only alphabets and space.";
                error = true;
            }

            if (!last_name.isEmpty()) {
                if (last_name.length() > 30) {
                    file_error = file_error + "<br/>XLS Row No." + count + ": Please provide last name with length less than 30 characters.";
                    error = true;
                } else if (!last_name.matches(name_reg)) {
                    file_error = file_error + "<br/>XLS Row No." + count + ": Last name contain only alphabets and space.";
                    error = true;
                }
            }

            String exp = "[1-9][0-9]{9}";
            if (user_number.equals("") || user_number.length() < 10 || user_number.length() > 10) {
                file_error = file_error + "<br/>XLS Row No." + count + ": Please enter a valid 10 digits mobile number.";
                error = true;
            } else if (!user_number.matches(exp)) {
                file_error = file_error + "<br/>XLS Row No." + count + ": Please enter a valid 10 digits mobile number.";
                error = true;
            } else {
                user_number = user_number.split("\\.")[0];
                for (int x = 0; x < user_number.length(); x++) {
                    if (!Character.isDigit(user_number.charAt(x))) {
                        file_error = file_error + "<br/>XLS Row No." + count + ": Please enter a valid 10 digits mobile number starting with 9, 8 or 7.";
                        error = true;
                        break;
                    }
                }
            }

            if (user_status.equals("")) {
                file_error = file_error + "<br/>XLS Row No." + count + ": Please provide user status as 'active' or 'inactive'";
                error = true;
            }

            ResultSet resultSet = statement.executeQuery("select user_id from user_account where mobile_no='" + user_number + "'");
            if (resultSet.next()) {
                file_error = file_error + "<br/>XLS Row No." + count + ": Mobile number entered is already in use. Please enter a different number.";
                error = true;
            }

            if (!email_id.isEmpty()) {
                String emailReg = "^([\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4})?$";
                if (!email_id.matches(emailReg)) {
                    file_error = file_error + "<br/>XLS Row No." + count + ": Please provide a valid email address.";
                    error = true;
                } else if (email_id.length() > 30) {
                    file_error = file_error + "<br/>XLS Row No." + count + ": Please provide email id with length less than 30 characters.";
                    error = true;
                } else {
                    ResultSet resultSet1 = statement.executeQuery("select user_id from user_account where email_id='" + email_id + "'");
                    if (resultSet1.next()) {
                        file_error = file_error + "<br/>XLS Row No." + count + ": Email id entered is already in use. Please choose a different email id.";
                        error = true;
                    }
                }
            }

            ///changes are required
            String user_type_id = null;
            ResultSet resultSet3 = statement.executeQuery("select * from user_type where user_type_name='" + user_type + "'");
            if (resultSet3.next()) {
                user_type_id = resultSet3.getString("user_type_id");
                type.add(user_type_id);
            }

            if (!file_error.equals("")) {
                continue;
            } else {
                URL connectURL = new URL(password_path);
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        connectURL.openStream()));

                String inputLine;
                StringBuilder password = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    password.append(inputLine);
                }
                in.close();
                int uid = 0;
                String encrypted = AESCrypt.bytesToHex(aESCrypt.encrypt(password.toString()));
                passwords.add(password.toString());

                String query = "insert into user_account(user_type_id,first_name,last_name,mobile_no,email_id,status,login_id,password,login_flag,last_gen_pw_ts,last_updated_ts)values('" + user_type_id + "','" + first_name + "','" + last_name + "','" + user_number + "','" + email_id + "','" + user_status + "','" + login_id + "','" + encrypted + "',0,'" + ist.getLastUpdatedts() + "','" + ist.getLastUpdatedts() + "')";
                //  inserts.add(query);

                statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
             //     connection.commit();
                ResultSet rs2 = statement.getGeneratedKeys();
                if (rs2.next()) {
                    uid = rs2.getInt(1);
                }
                if (!group_name.equals("")) {
                    String query1 = "select group_id from user_group where group_name='" + group_name + "'";
                    ResultSet resultset1 = statement.executeQuery(query1);
                    if (resultset1.next()) {
                        int gid = 0;
                        gid = Integer.parseInt(resultset1.getString("group_id"));
                        statement.executeUpdate("insert into user_group_allocation(group_id,user_id,last_updated_ts)values('" + gid + "','" + uid + "','" + ist.getLastUpdatedts() + "')");
                    } else {
                        int gid = 0;
                        String query4 = "insert into user_group(group_name,group_desc,status,last_updated_ts)values('" + group_name + "','','Active','" + ist.getLastUpdatedts() + "')";
                        statement.executeUpdate(query4, Statement.RETURN_GENERATED_KEYS);
                        ResultSet rs3 = statement.getGeneratedKeys();
                        if (rs3.next()) {
                            gid = rs3.getInt(1);
                        }
                        statement.executeUpdate("insert into user_group_allocation(group_id,user_id,last_updated_ts)values('" + gid + "','" + uid + "','" + ist.getLastUpdatedts() + "')");
                    }
                }
            }
        }
        if (!file_error.equals("")) {
            throw new Exception();
        }
      connection.commit();

//           for (int i = 0; i < names.size(); i++) {
//                SendSMS(names.get(i), numbers.get(i), passwords.get(i), login_ids.get(i));
//            }
//            for (int i = 0; i < email_ids.size(); i++) {
//                SendMail(names.get(i), email_ids.get(i), passwords.get(i), login_ids.get(i));
//            }
    }}

0 个答案:

没有答案