首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >记录存在+文本字段条件的问题

记录存在+文本字段条件的问题
EN

Stack Overflow用户
提问于 2019-03-31 19:39:16
回答 1查看 90关注 0票数 0

基本上,A有一个注册界面,它应该清空文件和某些条件,如果数据库中存在记录,它首先检查文本字段是否为空,如下所示:

代码语言:javascript
复制
 private void confirmActionPerformed(java.awt.event.ActionEvent evt) {                                        
            //  String f= "jdbc:derby://localhost:1527/BStest";
     String name=username.getText();
            String gender=null;
            String passw=String.valueOf(pass.getPassword());
             String repassw=String.valueOf(repass.getPassword());
            String phone2=phone.getText();
            String emaill=email.getText();
            boolean checkage=false,checknum=false,checkcap=false,checklaw=false,checkemail=false,checkdomain=false;
            boolean checklen=false,checkbfat=false,checkpass=false,checkchar=false,checkgender=false;
                boolean    checkempty=true;

              if(name.isEmpty()){//is text field empty 
              checkempty=false;
              JOptionPane.showMessageDialog(null,"Add a username!");}
          if(passw.isEmpty()){//is text field empty 
              checkempty=false;
              JOptionPane.showMessageDialog(null,"Add a Password!");}
           if(!repassw.equals(passw)){//confirmed password is the same for password
               checkempty=false;
               JOptionPane.showMessageDialog(null,"Type password Again!");
           }
           if(phone2.isEmpty()){//is text field empty 
               checkempty=false;
               JOptionPane.showMessageDialog(null,"Add Phone number !");
           }
           if(emaill.isEmpty()){//is text field empty 
               checkempty=false;
               JOptionPane.showMessageDialog(null,"Add email please !");
           }

           if (!m.isSelected()&& !female.isSelected()){//no gender selected
               checkempty=false;
               JOptionPane.showMessageDialog(null,"Choose a gender !!");}
          else if (m.isSelected()&& female.isSelected()){//both selected it shoud be only one
              checkempty=false;
               JOptionPane.showMessageDialog(null,"Select only  One !!");}
          if(age.getText().isEmpty()){//is age text field has no input
             checkempty=false;
            JOptionPane.showMessageDialog(null,"Enter your age !!");}

然后检查每个文本字段的标准,如下面的注释所示

代码语言:javascript
复制
if (m.isSelected()){// is female or male selected
               checkgender=true;
                 gender="Male";
             }
           else if (female.isSelected()){
               checkgender=true;
                 gender="Female";
             }
            int agee =Integer.parseInt(age.getText());      
            char c,c2=emaill.charAt(0);
            String zereofive=phone2.substring(0, 2);//start with 05
         String bfat = emaill.substring(0,emaill .indexOf("@"));//digits berfore @
String domain = emaill.substring(emaill .indexOf("@") + 1);//check domain
       if(Character.isLetter(c2))//is first char off email iis letter
            checkchar=true;
           else
           JOptionPane.showMessageDialog(null,"Emails only start with letters");


     if (phone2.length()==10 &&  zereofive.equals("05"))//check length of phone number 
          checklen=true;
        else
          JOptionPane.showMessageDialog(null,"enter 10 digits for the phone number and starts with 05");
if(bfat.length()>=6 || bfat.length()<=15){//check digits before @
   checkemail=true;
}
   if(domain.equals("gmail.com") || domain.equals("hotmail.com")){//check domain of email 
       checkdomain=true;
   }
       else
    JOptionPane.showMessageDialog(null,"Email domain is wrong");
   if(agee>=18)//only can register in 18 or above
                checkage=true;
          else
              JOptionPane.showMessageDialog(null,"You can't register because you are under 18. ");

    if(passw.length()>7){// password at least 8 digit  at least one captial and one small letter
           checklen=true;
          for (int i=0;i<passw.length();i++){
              c=passw.charAt(i);
          if(Character.isDigit(c))
          checknum=true;
          else if (Character.isUpperCase(c))
              checkcap=true;
          else if (Character.isLowerCase(c))
              checklaw=true;
          if(checknum && checkcap && checklaw )
              checkpass=true;

          }}
    if(checkpass)//check of all 3 crietria of pass word is coorrect 
        checkpass=true;
          else
            JOptionPane.showMessageDialog(null,"password must be at least 8 digits \n at least 1 Upper Case letter \n at least 1 Lower Case letter \n at least 1 number \n");

最后,如果满足条件且记录不存在,则将其存储在数据库中

代码语言:javascript
复制
    PreparedStatement reg,exist;
           String query="INSERT INTO customer (Cu_name, Cu_password, Cu_age, Cu_gender, Cu_email, Cu_phone) VALUES (?, ?, ?, ?, ?, ?)";//enter user info in database
           String record_exists="SELECT * FROM customer where Cu_name=? and Cu_password= ? and Cu_age=? and Cu_gender=? and Cu_email=? and Cu_phone=?";
           try{
               String f= "jdbc:derby://localhost:1527/BStest";
                Connection connection = DriverManager.getConnection(
            f, "meme", "Moudhi102"); 
          reg=connection.prepareStatement(query);
          exist=connection.prepareStatement(record_exists);
          reg.setString(1, name);
           reg.setString(2, passw);
             reg.setInt(3, agee);     
              reg.setString(4, gender);
               reg.setString(5, emaill);
                reg.setString(6, phone2);
                 exist.setString(1, name);
           exist.setString(2, passw);
             exist.setInt(3, agee);     
              exist.setString(4, gender);
               exist.setString(5, emaill);
                exist.setString(6, phone2);
                rs=exist.executeQuery();

                if(rs==null){            
       if(checkpass &&checkage && !checkdomain &&  !checkemail && !checklen && checkchar && !checkgender && checkempty    ){//if all criteria justified then add it to database

                   reg.executeUpdate();
                    JOptionPane.showMessageDialog(null,"Complete! new user added !! "); 

    }

        }else//else it can't be added
   {
       JOptionPane.showMessageDialog(null, "Record already exists");
    }
           }
           catch(SQLException ex){
            JOptionPane.showMessageDialog(null,ex);
        }

问题是,如果数据库中已经存在记录,它不会显示消息,如果我在年龄+电话+电子邮件中输入空文本,它会显示消息,表明它是空的,但在NetBeans本身中,会在输出区域中显示一条错误消息,如下所示

代码语言:javascript
复制
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:592)
    at java.lang.Integer.parseInt(Integer.java:615)
    at event_system.Sign_up.confirmActionPerformed(Sign_up.java:275)
    at event_system.Sign_up.access$000(Sign_up.java:20)
    at event_system.Sign_up$1.actionPerformed(Sign_up.java:70)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)

并且不执行这三个字段的编码部分并显示它们的消息,即使对于密码,如果不满足条件并且其他字段输入是ok的,则显示记录的连续消息存在并且无法注册检查/填充您information.Please帮助我我卡住了,无法弄清楚

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-01 08:52:44

在考虑处理其他问题之前,请先处理您的异常,因为这将阻止代码的其他部分从异常点运行,从而成为此时所有问题的根本原因。

不能将空字符串("")传递给Integer#parseInt()方法:

代码语言:javascript
复制
int agee = Integer.parseInt(age.getText());

如果要包含年龄的文本字段为空,则JTextField#getText()方法将返回空字符串("")。如果您将其提供给Integer#parseInt()方法(就像您在上面的代码中所做的那样),或者除整数值以外的任何,那么就会生成一个NumberFormatException。您需要注意这种可能的情况,使用Ternary Operator (也称为条件运算符)可能就是您需要的全部:

代码语言:javascript
复制
int agee = age.getText().trim().equals("") ? 0 : Integer.parseInt(age.getText().trim());

但是,这并没有涵盖这样一个事实,即在Age文本字段中可能意外提供了一个alpha字符。为了解决这个问题,最好这样做:

代码语言:javascript
复制
String theAge = age.trim().getText();
int agee = 0;
// Regular Expression used to ensure a Integer 
// Numerical String value was supplied.
if (theAge.matches("\\d+")) {
    agee = Integer.parseInt(theAge);
}

在上面的代码行中,如果年龄文本字段不包含任何内容或包含空格,则为agee变量提供一个整数0值,否则将对文本字段的内容使用Integer.parseInt()方法来填充agee变量。

旁注:

您为每个文本字段使用了大量的布尔型标志,以确保有效性和其他功能。在我看来,你实际上不需要它们中的任何一个,因为你正在检查所有的字段,并且你的要求是所有这些字段都被实际填充:

代码语言:javascript
复制
boolean checkage=false, checknum=false, checkcap=false, checklaw=false, 
        checkemail=false,checkdomain=false;
boolean checklen=false, checkbfat=false, checkpass=false, checkchar=false, 
        checkgender=false;
boolean checkempty=true;

我会把它们都去掉,而且根本不用旗帜。如果在代码中的任何时候,任何一个文本字段都不符合confirmActionPerformed()事件中的有效性,那么就不应该从数据库中读取任何内容,也不应该将任何内容写入数据库。当检查字段的有效性并且其中任何字段失败时,您只需通过消息框显示事实,然后当用户选择OK按钮时,我们将焦点设置在当前正在检查的文本字段(age.requestFocus();)上,然后使用return;语句退出事件。除非您的所有文本字段都通过了有效性检查,否则永远无法访问数据库代码。您的事件代码可能如下所示:

代码语言:javascript
复制
private void confirmActionPerformed(java.awt.event.ActionEvent evt) {
    //  String f= "jdbc:derby://localhost:1527/BStest";
    String name = username.getText().trim();
    String gender = null;
    String passw = String.valueOf(pass.getPassword());
    String repassw = String.valueOf(repass.getPassword());
    String phone2 = phone.getText().trim();
    String emaill = email.getText().trim();

    // NAME
    //is Name text field empty 
    if (name.isEmpty()) {
        JOptionPane.showMessageDialog(null, "Add a username!");
        username.requestFocus();
        return;
    }

    // PASSWORD
    //is Password field empty 
    if (passw.isEmpty()) {
        JOptionPane.showMessageDialog(null, "Add a Password!");
        pass.requestFocus();
        return;
    }
    /* A Regular Expression is used here to ensure your desired
       password rules apply - Minimum of 8 characters in length,
       at least 1 Uppercase Letter, at least 1 Lowercase letter, 
       at least 1 digit.   */
    if (!passw.matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$")) {
        JOptionPane.showMessageDialog(null, "Password must be:\n\n"
                + "- At least 8 characters in length,\n"
                + "- Contain at least 1 Uppercase letter,\n"
                + "- Contain at least 1 Lowercase letter,\n"
                + "- Contain at least 1 number.");
        pass.requestFocus();
        return;
    }
    // confirmed password is the same for password
    if (!repassw.equals(passw)) {
        JOptionPane.showMessageDialog(null, "Type password Again!");
        repass.requestFocus();
        return;
    }

    // PHONE
    //is phone text field empty 
    if (phone2.isEmpty()) {//is text field empty 
        JOptionPane.showMessageDialog(null, "Add Phone number !");
        phone.requestFocus();
        return;
    }
    // starts with 05
    String zereofive = phone2.substring(0, 2);
    // check length of phone number 
    if (phone2.length() != 10 && !zereofive.equals("05")) {
        JOptionPane.showMessageDialog(null, "enter 10 digits for the phone number and starts with 05");
        phone.requestFocus();
        return;
    }

    // E-MAIL
    //is E-Mail text field empty
    if (emaill.isEmpty()) {
        JOptionPane.showMessageDialog(null, "Add email please !");
        email.requestFocus();
        return;
    }
    // E-Mail
    char c, c2 = emaill.charAt(0);
    String bfat = emaill.substring(0, emaill.indexOf("@"));//digits berfore @
    String domain = emaill.substring(emaill.indexOf("@") + 1);//check domain
    // is first char off email a letter
    if (!Character.isLetter(c2)) {
        JOptionPane.showMessageDialog(null, "Emails can only start with letters!");
        email.requestFocus();
        return;
    }
    //check digits before @
    if (bfat.length() < 6 || bfat.length() > 15) {
        JOptionPane.showMessageDialog(null, "Invalid digits in Email address!");
        email.requestFocus();
        return;
    }
    //check domain of email
    if (!domain.equals("gmail.com") && !domain.equals("hotmail.com")) {
        JOptionPane.showMessageDialog(null, "Email domain is wrong!");
        email.requestFocus();
        return;
    }

    // GENDER
    //no gender selected
    if (!m.isSelected() && !female.isSelected()) {
        JOptionPane.showMessageDialog(null, "Choose a Gender!!");
        return;
    }
    //both Genders are selected where it shoud be only one
    else if (m.isSelected() && female.isSelected()) {
        JOptionPane.showMessageDialog(null, "Select only One Gender!!");
        return;
    }
    // is female or male selected
    if (m.isSelected()) {
        gender = "Male";
    }
    else if (female.isSelected()) {
        gender = "Female";
    }

    // AGE
    //is Age text field empty
    String theAge = age.trim().getText();
    if (theAge.isEmpty()) {
        JOptionPane.showMessageDialog(null, "Enter your age !!");
        age.requestFocus();
        return;
    }
    int agee = 0;    // Default
    // Regular Expression used to ensure a Integer 
    // Numerical String value was supplied.
    if (theAge.matches("\\d+")) {
        agee = Integer.parseInt(theAge);
    }
    // only 18 + can register
    if (agee < 18) {
        JOptionPane.showMessageDialog(null, "You can't register because you are under 18!");
        age.requestFocus();
        return;
    }

    // DATABASE
    Connection connection = null;
    PreparedStatement reg, exist;
    ResultSet rs = null;
    String query = "INSERT INTO customer (Cu_name, Cu_password, Cu_age, Cu_gender, Cu_email, Cu_phone) VALUES (?, ?, ?, ?, ?, ?)";//enter user info in database
    String record_exists = "SELECT * FROM customer where Cu_name=? and Cu_password= ? and Cu_age=? and Cu_gender=? and Cu_email=? and Cu_phone=?";
    try {
        String f = "jdbc:derby://localhost:1527/BStest";
        connection = DriverManager.getConnection(f, "meme", "Moudhi102");
        reg = connection.prepareStatement(query);
        exist = connection.prepareStatement(record_exists);
        reg.setString(1, name);
        reg.setString(2, passw);
        reg.setInt(3, agee);
        reg.setString(4, gender);
        reg.setString(5, emaill);
        reg.setString(6, phone2);

        exist.setString(1, name);
        exist.setString(2, passw);
        exist.setInt(3, agee);
        exist.setString(4, gender);
        exist.setString(5, emaill);
        exist.setString(6, phone2);
        rs = exist.executeQuery();

        if (rs == null) {
            reg.executeUpdate();
            JOptionPane.showMessageDialog(null, "Complete! new user added !! ");
        }
        // User Already Exists In Database
        else {
            JOptionPane.showMessageDialog(null, "User already exists");
        }
    }
    catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, ex);
    }
    finally {
        if (reg != null) {
            reg.close();
        }
        if (rs != null) {
            rs.close();
        }
        if (connection != null) {
            connection.close();
        }
    }

}

在查询WHERE子句中检查特定用户的重复记录的数据库记录时,年龄可能不一定是一个很好的标准。它只强制要求每条记录只在一年内有效。事情会变,年龄、电子邮件、电话号码等都是经常会改变的东西。如果只有名称和密码用于访问有效性(这对于大多数情况应该足够),而其余条件仅用于指示需要对用户数据帐户进行更新,则该概念显然没有错。

您应该认为提供的密码是散列的,并且它是存储在数据库中的散列。当用户提供密码时,该密码将被散列,并与数据库中已存储的散列进行比较。任何人,包括你自己,都不应该知道真正的密码是什么。只有用户才应该知道密码可能是什么。jBCrypt在这方面做得很好。要使用此库对密码进行哈希处理:

导入:

代码语言:javascript
复制
import org.mindrot.jbcrypt.BCrypt;
import static org.mindrot.jbcrypt.BCrypt.hashpw;

类成员变量:

代码语言:javascript
复制
// Define the BCrypt WORKLOAD to use when generating
// password hashes. 10-31 is a valid value.
private static final int WORKLOAD = 12;

要对明文密码进行散列以存储在数据库中,请执行以下操作:

代码语言:javascript
复制
/**
 * This method can be used to generate a string representing an account
 * password suitable for storing in a database. It will be an OpenBSD-style
 * crypt(3) formatted hash string of length=60 The BCrypt WORKLOAD is
 * specified in the above static variable, a value from 10 to 31. A WORKLOAD
 * of 12 is a very reasonably safe default. This automatically handles
 * secure 128-bit salt generation and storage within the hash.
 *
 * @param password_plaintext The account's plaintext password as provided
 *                           during account creation, or when changing an
 *                           account's password.
 *
 * @return String - a string of length 60 that is the bcrypt hashed password
 *         in crypt(3) format.
 */
public static String hashPassword(String password_plaintext) {
    String salt = BCrypt.gensalt(WORKLOAD);
    String hashedPassword = hashpw(password_plaintext, salt);
    return hashedPassword;
}

要使用数据库中存储的哈希检查明文密码,请执行以下操作:

代码语言:javascript
复制
/**
 * This method can be used to verify a computed hash from a plaintext (e.g.
 * during a login request) with that of a stored hash from a database. The
 * password hash from the database must be passed as the second argument.
 *
 * @param passwordAsPlainText The accounts plaintext password, as provided
 *                            during a login request
 *
 * @param storedEncryption    The accounts stored password hash, retrieved
 *                            from the authorization database
 *
 * @return boolean - true if the password matches the password of the stored
 *         hash, false otherwise
 */
/*
public static boolean checkPassword(String passwordAsPlainText, String storedEncryption) {
    boolean passwordVerification;

    if (null == storedEncryption || !storedEncryption.startsWith("$2a$")) {
        throw new java.lang.IllegalArgumentException(
                "Invalid encryption provided for comparison");
    }

    passwordVerification = checkpw(passwordAsPlainText, storedEncryption);

    return passwordVerification;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55440519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档