java android中的登录表单验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12345225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:30:18  来源:igfitidea点击:

Login form validation in android

javaandroidvalidation

提问by Krishna Veni

I have developed one login form in Android. I have used validation here. I have to fill anyone (username or password) then my app should display Success!and should move to other activity.

我在 Android 中开发了一种登录表单。我在这里使用了验证。我必须填写任何人(用户名或密码)然后我的应用程序应该显示成功!并且应该转向其他活动。

But, if both fields are empty, the success message should not be displayed and it should display Login fail!!!.

但是,如果两个字段都为空,则不应显示成功消息,而应显示登录失败!!!.

Please help me this.

请帮我这个。

This is my webservice code:

这是我的网络服务代码:

public class XcartLogin {
    public String authentication(String userName, String password) {
        String retrievedUserName = "";
        String retrievedPassword = "";
        String status = "";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xcart432-pro", "root", "");
            PreparedStatement statement = con.prepareStatement("SELECT * FROM xcart_customers WHERE login = '" + userName + "'");
            ResultSet result = statement.executeQuery();
            while (result.next()) {
                retrievedUserName = result.getString("login");
                retrievedPassword = result.getString("password");
            }
            if (retrievedUserName.equals(userName) && retrievedPassword.equals(password)) {
                status = "Success!";
            } else {
                status = "Login fail!!!";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return status;
    }
}

This is validation for my android code:

这是对我的 android 代码的验证:

if(status.equals("Success!"))
    {
        // ADD  to save  and  read next time
        String strUserName = userName.getText().toString().trim();
        String strPassword = userPassword.getText().toString().trim();
        if (null == strUserName || strUserName.length() == 0)
        {
            // showToast("Enter Your Name");
            userName.setError( "username is required!" );
            isUserValidated = false;
        }
        if (null == strPassword || strPassword.length() == 0)
        {
            // showToast("Enter Your Password");
            isPasswordValidated = false;
            userPassword.setError( "password is required!" );
        } 
    }

回答by Matthew Quiros

Before the if(status.equals("Success!"))statement in your validation code, you should do this first to avoid querying the database if any of the text fields are empty in the first place:

if(status.equals("Success!"))验证代码中的语句之前,您应该首先执行此操作以避免在任何文本字段首先为空时查询数据库:

boolean errorOccurred = false;
if (strUserName.equals("")) {
    userName.setError("Username is required!");
    errorOccurred = true;
}

if (strPassword.equals("")) {
    userName.setError("Password is required!");
    errorOccurred = true;
}

if (errorOccurred) {
    return; // avoids executing the part of your code which queries the db
}

Checking for whether the input fields' values are nullis quite pointless since if they don't contain anything, it will only be an empty string, or "". Then, to simplify your webservice code...

检查输入字段的值是否null毫无意义,因为如果它们不包含任何内容,它只会是一个空字符串,或者"". 然后,为了简化您的网络服务代码...

if (result.next()) { // use if instead of while, because ideally, only ONE record should
                     // be returned and hence, no need to loop;

    // then, just get the corresponding password
    retrievedPassword = result.getString("password");
}

if (retrievedPassword.equals(password)) {
    status = "Success!";
}

Further suggestion: put "Success!" in a Stringconstant and use that instead of the literal value. You have lesser chances of committing mistakes this way and makes editing your code easier.

进一步的建议:输入“成功!” 在String常量中并使用它而不是文字值。以这种方式犯错的可能性较小,并且可以更轻松地编辑代码。

回答by G_S

Try using this condition:

尝试使用此条件:

if(retrievedUserName.equals(userName)&&retrievedPassword.equals(password)&&!(retrievedUserName.equals("") && retrievedPassword.equals("")))

Instead of your condition:

而不是你的条件:

if(retrievedUserName.equals(userName)&&retrievedPassword.equals(password))

回答by Sujay

First of all, the way you're using the PreparedStatement is incorrect. Here's how you should modify it:

首先,您使用 PreparedStatement 的方式不正确。以下是您应该如何修改它:

PreparedStatement statement =  con.prepareStatement("SELECT * FROM xcart_customers WHERE login = ?");

You would then use the setString(int paramIndex, String value)to set the value and then call the executeQuery()method. Something like this:

然后,您将使用setString(int paramIndex, String value)来设置值,然后调用该executeQuery()方法。像这样的东西:

PreparedStatement statement =  con.prepareStatement("SELECT * FROM xcart_customers WHERE login = ?");
statement.setString(1, userName);

ResultSet result = statement.executeQuery();

This is secure and the actual way to use a PreparedStatement in your code.

这是安全的,也是在代码中使用 PreparedStatement 的实际方法。

Now, to test for your requirement, you should do something like this:

现在,要测试您的要求,您应该执行以下操作:

if(userName.equals(retrievedUserName)&&password.equals(retrievedPassword)&&!("".equals(retrievedUserName) && "".equals(retrievedPassword)))

Notice that I am checking userNameand passwordagainst retrievedUserNameand retrievedPasswordand notthe other way round because there retrievedUserNameor retrievedPasswordmay be null as per the Javadocfor getString(int).

请注意,我检查的userName密码retrievedUserNameretrievedPassword没有倒过来,因为有retrievedUserNameretrievedPassword可以为空按在的JavadocgetString(int)

Returns: the column value; if the value is SQL NULL, the value returned is null

返回: 列值;如果值为 SQL NULL,则返回值为 null

If the value were to come as null, then you would be dealing with a NullPointerException, which I guess you might want to avoid. Also, for the very same reason, you might want to check the arguments for null value as before you even try to query the database.

如果该值为 null,那么您将处理 a NullPointerException,我想您可能想要避免这种情况。此外,出于同样的原因,您可能希望在尝试查询数据库之前检查空值的参数。