我在Servlet中创建了一个简单的注册和登录。我做了注册部分,但是每当尝试使用相同的信息登录时,我都无法验证和登录。
这是我的用户信息验证:
import java.sql.*;
public class ValidateUser {
public static boolean checkLogin(String email, String password){
boolean isUser = false;
String user = "postgres";
String pass = "postgres";
String jdbcUrl = "jdbc:postgresql://127.0.0.1:5432/regs";
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String sql = "select * from regs where email = ? and password = ?";
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(jdbcUrl, user, pass);
connection.setAutoCommit(false);
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, email);
preparedStatement.setString(2, password);
resultSet = preparedStatement.executeQuery();
isUser = resultSet.next();
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return isUser;
}
}
这是Login Servlet:
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "Login", urlPatterns = "/login")
public class Login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String email = request.getParameter("email");
String password = request.getParameter("password");
if (ValidateUser.checkLogin(email, password)) {
out.println("You successfully logged-in");
} else {
response.sendRedirect("login.jsp");
// out.println("Bad username or password");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
使用Login.java时,用户名和密码仅为null,因此无法登录
在您的Servlet中导入ValidateUser类。在您的checkLogin函数中,您将返回一个对象,但在您的servlet中,您将使用
检查布尔值。如果(ValidateUser.checkLogin(电子邮件,密码))
更改您的checkLogin功能。
如果(!resultSet.first())返回False
catch(SQLException e){}
返回真
尝试一下,确保数据库的用户名,密码正确,表名和列名与您在数据库中创建的表匹配。
String sql =“ SELECT * FROM REGS WHERE email ='” +电子邮件+“'AND密码='” +密码+“'”;