e có đag tạo 1 form login với servlet , với việc check username và password lấy từ database bằng hàm CheckLogin() nhưng k hoạt động , mặc dù e có thử hàm testdb để kiểm tra dữ liệu từ hàm CheckLogin() xem đã có dữ liệu chưa thì nó vẫn in ra đúng ạ
public Acount checkLogin(String username, String password) throws SQLException {
Acount a = null;
try {
// String url = "jdbc:sqlserver://" +serverName + ":1433;DatabaseName=" + dbName + ";encrypt=true;trustServerCertificate=true";
Connection con = Dbcontext.getConnection();
String sql = "SELECT * FROM Acount where username = ? and pasword = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if (rs.next()) {// lay tung ban ghi
a = new Acount(rs.getString("username").trim(), rs.getString("pasword").trim());
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return a;
}
Dbcontext kết nối sql
public class Dbcontext {
public static Connection getConnection()throws Exception {
String serverName = "DESKTOP-H42IUA3\\SQLEXPRESS";
String dbName = "btl";
String portNumber = "1433";
String instance="";//LEAVE THIS ONE EMPTY IF YOUR SQL IS A SINGLE INSTANCE
String userID = "sa";
String password = "******";
// String url = "jdbc:sqlserver://"+serverName+":"+portNumber + "\\" + instance +";databaseName="+dbName+ ";encrypt=true;trustServerCertificate=true";
// if(instance == null || instance.trim().isEmpty())
String url = "jdbc:sqlserver://" + serverName + ":1433;DatabaseName=" + dbName + ";encrypt=true;trustServerCertificate=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
return DriverManager.getConnection(url, userID, password);
}
Form loginSErvlet ạ
@WebServlet(name = "LoginForm", value = "/Login")
public class LoginForm extends HttpServlet {
private AcountDao acountDao;
@Override
public void init() {
acountDao = new AcountDao();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
boolean check = false;
String u = request.getParameter("uname").trim();
String p = request.getParameter("psw").trim();
System.out.println("username: " + u);
System.out.println("password: " + p);
if (acountDao == null) {
acountDao = new AcountDao();
}
Acount a = acountDao.checkLogin(u, p);
if (a == null) {
request.getRequestDispatcher("web/login.jsp").forward(request, response);
} else {
request.getRequestDispatcher("web/home.jsp").forward(request, response);
}
} catch (Exception e) {
}
}
testDB() in ra đã có dữ liệu ạ
public class testdb {
public static void main(String[] args) throws SQLException {
try {
AcountDao login = new AcountDao();
Acount l = login.checkLogin("hung", "1512");// mật khẩu tk
System.out.println(l.getUsername() + l.getPassword());
} catch (Exception e) {
e.printStackTrace();
}
}