0

程序是否可以验证用户输入的帐户凭据是否属于某种帐户?如果是,如何?例如:

数据库

username                      password
jake (admin)                   qwerty
anna (student)                 asdf

如果用户输入 jake 和 qwerty 作为登录凭据,那么他将能够访问管理菜单,并且当他使用学生帐户 anna 和 asdf 时,他将能够访问学生菜单。

登录按钮:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    //str = JOptionPane.showInputDialog(this, "Enter id number: ");
    user = jTextField1.getText();
    pass = jPasswordField1.getPassword();
    login();
}

功能

private void login() {

    try {
        if ((user != null)&&(pass != null)) {
            sql = "Select * from users_table Where username='" + user + "' and password='" + pass + "'";
            ResultSet rs = stmt.executeQuery(sql);
            if( rs.next()) {
                JOptionPane.showMessageDialog(null, "A basic JOptionPane message dialog");
            } else {
                //in this case enter when  result size is zero  it means user is invalid
            }
        }
    } catch (SQLException err) {
        JOptionPane.showMessageDialog(this, err.getMessage());
    }
}
4

1 回答 1

2

Gian,通常在您的用户数据库中有某种“角色”列。

例如:

username      password       role
jake          qwerty         admin
anna          asdf           student

当您在结果集中获得结果时,请从表中读取“角色”字段并根据该字段进行功能差异。

        ResultSet rs = stmt.executeQuery(sql);
        if( rs.next()) {
            if ("admin".equals(rs.getString("role")) {
                 // ...
            } else { 
                 // ...
            }
            JOptionPane.showMessageDialog(null, "A basic JOptionPane message dialog");
        } else {
            //in this case enter when  result size is zero  it means user is invalid
        }

祝你好运!

PS注意SQL注入攻击!!如果我按如下方式输入用户名会发生什么?你怎么能防止它呢?

'; delete from users_table;
于 2013-02-21T20:08:29.273 回答