gpt4 book ai didi

java - 验证电子邮件地址和密码

转载 作者:行者123 更新时间:2023-12-02 06:08:44 24 4
gpt4 key购买 nike

如何在用户登录时验证特定电子邮件和密码?

protected void doPost(HttpServletRequest request, HttpServletResponse res) throws IOException, ServletException {

String email=request.getParameter("email");
String pass=request.getParameter("pass");

OutputStream out = res.getOutputStream();

try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8080/college", "root", "root");
Statement st=con.createStatement();
String strSQL = "SELECT email,password FROM student";

在 SELECT 语句之后如何继续?我更喜欢使用 if...else 语句来进行验证。

最佳答案

首先正确关闭所有连接资源 - 使用 Java 7 try-with-resources。

这是一个简单的例子:

final String email = request.getParameter("email");
final String pass = request.getParameter("pass");
try (final Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8080/student", "root", "root");
final PreparedStatement statement = con.prepareStatement("SELECT COUNT(*) AS count FROM student WHERE email=? AND password=?");) {
statement.setString(1, email);
statement.setString(2, pass);
try (final ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
final int rows = resultSet.getInt("count");
if (rows > 1) {
throw new IllegalStateException("More than one row returned!");
}
boolean validUser = rows == 1;
}
}
}

但实际上您应该在数据库中对密码进行哈希处理。使用类似 jBcrypt 的内容。您的代码将如下所示:

final String email = request.getParameter("email");
final String pass = request.getParameter("pass");
try (final Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8080/student", "root", "root");
final PreparedStatement statement = con.prepareStatement("SELECT pass FROM student WHERE email=?");) {
statement.setString(1, email);
statement.setString(2, pass);
try (final ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
final String hash = resultSet.getString("pass");
final boolean valid = BCrypt.checkpw(pass, hash);
}
}
}

显然,如果查询没有返回行,您需要添加错误检查。您还需要检查是否仅返回一行。但我把它留作练习。

关于java - 验证电子邮件地址和密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22062974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com