dimanche 14 mars 2021

JavaEE does not throw SQLException when primary key is duplicated

I am studying on a Java Web Application with JavaEE (not SPRING). But I have ran into a problem that my application doesn't throw SQLException when a row is inserted into table with duplicated primary key.

In details, I have a DAO class AccountInfoDAO.java with a createNewAccount method:

public boolean createNewAccount(String username, String password, 
                                String fullName, boolean role) 
    throws NamingException, SQLException {
    boolean result = false;
    Connection con = null;
    PreparedStatement stmt = null;
    int iCount = 0;
    
    try {
        con = DBHelpers.makeConnection();
        if (con != null) {
            
            String queryStr = "INSERT INTO "
                    + "accountInfo(username, password, lastname, isAdmin) "
                    + "VALUES(?, ?, ?, ?)";
            
            stmt = con.prepareStatement(queryStr);
            stmt.setString(1, username);
            stmt.setString(2, password);
            stmt.setNString(3, fullName);
            stmt.setBoolean(4, role);
            
            iCount = stmt.executeUpdate();
            
            if (iCount > 0) {
                result = true;
            }
        } // EndIf Connected
    } finally {
        if (stmt != null) {
            stmt.close();
        }
        if (con != null) {
            con.close();
        }
        return result;
    }
}

And my functional Servlet CreateNewAccountServlet.java with the processRequest method:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    
    String username = request.getParameter("txtUsername");
    String password = request.getParameter("txtPassword");
    String confirm = request.getParameter("txtConfirm");
    String fullname = request.getParameter("txtFullname");
    
    String url = ERROR_PAGE;
    
    AccountInfoCreateError errors = new AccountInfoCreateError();
    boolean foundErr = false;
    
    try {
        // 1. Check valid user input
        if (username.trim().length() < 6 || username.trim().length() > 30) {
            foundErr = true;
            errors.setUsernameLengthErr("Username requires input from 6 to 30 characters!");
        }
        
        if (password.trim().length() < 6 || username.trim().length() > 20) {
            foundErr = true;
            errors.setPasswordLengthErr("Password requires input from 6 to 20 characters!");
        } else if (!password.trim().equals(confirm.trim())) {
            foundErr = true;
            errors.setConfirmNotMatch("Confirm mus be matched with password!");
        }
        
        if (fullname.trim().length() < 2 || fullname.trim().length() > 50) {
            foundErr = true;
            errors.setFullNameLengthErr("Full name requires input from 2 to 50 characters!");
        }
        
        if (foundErr) {
            request.setAttribute("CREATE_ERROR", errors);
        } else {
            // 2. Call DAO
            AccountInfoDAO dao = new AccountInfoDAO();
            boolean result = dao.createNewAccount(username, password, fullname, false);
            if (result) {
                url = LOGIN_PAGE;
            }
        }
        
    } catch (SQLException ex) {
        String errMsg = ex.getMessage();
        log("CreateNewAccountServlet SQL: " + errMsg);
        if (errMsg.contains("Duplicate")) {
            errors.setUsernameIsExisted(username + " is existed");
            request.setAttribute("CREATE_ERROR", errors);
        }
        
    } catch (NamingException ex) {
        log("CreateNewAccountServlet Naming: " + ex.getMessage());
    }
    finally {
        RequestDispatcher rd = request.getRequestDispatcher(url);
        rd.forward(request, response);
        out.close();
    }
}

When I run my application, everything works well. A normal new account can be created and inserted into database successfully. But when I try to insert an account with a duplicated username (which is my primary key in the table), it doesn't throw SQLException, which is expected to happen. And my TomCat server does not write log, of course. All of my friends have done this with the exception thrown. I have tried to re-install my MS SQL Server, try to use different JDBC driver but the result is the same.

I am using JDK 8, NetBeans 8.2 RC, Apache Tomcat 8.0, MS SQL Server 2012 to implement this application.

Hope you can help me to fix this problem!

------- Update My table design in MS SQL Server My table design in MS SQL Server




Aucun commentaire:

Enregistrer un commentaire