0

我剪掉了这段代码,用于输入验证:

public void validaUserID(FacesContext context, UIComponent component, Object value) throws ValidatorException, SQLException {

        int findAccount = 0;

        if (ds == null) {
            throw new SQLException("Can't get data source");
        }
        // Initialize a connection to Oracle
        Connection conn = ds.getConnection();

        if (conn == null) {
            throw new SQLException("Can't get database connection");
        }

        // Convert Object into String
        int findValue = Integer.parseInt(value.toString()); 

        // With SQL statement get all settings and values
        PreparedStatement ps = conn.prepareStatement("SELECT * from USERS where USERID = ?");
        ps.setInt(1, findValue);
        try {
            //get data from database        
            ResultSet result = ps.executeQuery();
            while (result.next()) {
                // Put the the data from Oracle into Hash Map
                findAccount = result.getInt("USERID");
            }
        } finally {
            ps.close();
            conn.close();
        }

        // Compare the value from the user input and the Oracle data
        if (value.equals(findAccount)) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    value + " Session ID is already in use!", null));
        }
    }

由于某种原因,输入数据未与 Oracle 中的值正确比较。比较两个值的正确方法是什么?

4

3 回答 3

6

看起来您正在比较盒装整数。我会解开它们(即以原始形式获取它们)并做==而不是.equals.

于 2012-06-23T15:50:10.340 回答
1

Objects are compared using .equals() ,and String is an object too, so they also have to be compared using .equals().

例如:

假设 s1 和 s2 为字符串。

s1.equals(s2);

Primitive variables are compared using ==由于 Wrapper 是 Objects,你需要将它们与 .equals() 进行比较but if you want to compare them using ==,然后你必须先将它们转换为它的 Primitive 形式。

例如:

整数 a = 5;

int i = 新整数(a);

于 2012-06-23T16:03:40.070 回答
1

出色地。答案在于您的代码本身。

 if (value.equals(findAccount)) 

你可以这样写

  if (findValue == findAccount)) 

因为您已经将 Object Value展开为原始findValue

更清楚地说,equals() 被调用并仅传递给对象。您不能将对象与基元进行比较,反之亦然。

于 2012-06-23T16:32:10.630 回答