【问题标题】:How to validate username from MySql with JSP如何使用 JSP 从 MySql 验证用户名
【发布时间】:2012-04-03 14:21:32
【问题描述】:

大家好,我正在尝试使用用户在 html 中输入的用户名来验证数据库中的用户名,假设

un//be the variable where username entered now from html form is stored

现在如何从用户表中检索 uname 的所有列

uname //column name in mysql for usernames
user //table name in mysql

并检查天气用户名,即现在输入的用户名是否存在于数据库中 我正在使用

Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mebps","root","admin");
Statement stmt = (Statement) con.createStatement();
ResultSet rs = stmt.executeQuery("select un from userinfo");

while(rs.next())
{
if(rs.getString("uname") == un)
{
out.println("user is present");
}
}

【问题讨论】:

    标签: mysql database jsp jdbc


    【解决方案1】:

    至少有两个主要错误:

    1. 您正在通过== 比较字符串实例,而不是通过equals() 方法比较它们的值。正确的行是if (rs.getString("uname").equals(un))。

    2. 您没有让 DB 完成返回正确行的工作,而是将整个 DB 表复制到 Java 的内存中并在 Java 中进行比较。这是非常低效的。以智能方式利用 SQL 的强大功能,使其始终准确返回您需要的信息。例如有一个WHERE 子句。

    在不相关的说明中,您似乎在使用后没有正确关闭数据库资源。这将导致资源泄漏,这也是一个坏主意,因为它可能会导致您的应用程序长期崩溃。此外,列名uname 和un 也不相同。但我会假设它过于简单化了这个例子。

    这是一个小的重写:

    public boolean exist(String username) throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        boolean exist = false;
    
        try {
            connection = database.getConnection();
            statement = connection.prepareStatement("SELECT uname FROM userinfo WHERE uname=?");
            statement.setString(1, username);
            resultSet = statement.executeQuery();
            exist = resultSet.next();
        } finally {
            if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
            if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
            if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
        }
    
        return exist;
    }
    

    你看,如果有匹配,那么它返回true(至少一条记录),否则返回false(没有一条记录)。无需将整个表复制到 Java 的内存中并在 Java 中爬取。

    最后但同样重要的是,这段代码不属于 JSP 文件,而是属于普通的 Java 类,从 servlet 开始。另请参阅our servlets wiki page 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 2018-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      相关资源
      最近更新 更多