一、經常出現漏洞的sql語句 用戶名和密碼 一起同時查詢。
select * from users where username=‘abc’ and passwd=‘123’ or 1=‘1’
二、正確的sql語句先查詢數據庫根據用戶名查詢密碼,如果存在改用戶名,再看密碼是否相同。
"select passwd from users where username='" + name + "' limit 1";
正確代碼如下:
String name = req.getParameter("username");
String pwd = req.getParameter("pwd");
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// 加載數據庫驅動
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
// 得到數據庫連接
String url = "jdbc:mysql://localhost:3306/student";
String user = "root";
String password = "tianyejun6";
conn = DriverManager.getConnection(url, user, password);
// 創建statement
statement = conn.createStatement();
//sql語句
String sql = "select passwd from users where username='" + name + "' limit 1";
System.out.println(sql);
resultSet = statement.executeQuery(sql);
if (resultSet.next()) {
// 說明用戶真實存在
String passwd = resultSet.getString(1);
if (passwd.equals(pwd)) {// 說明用戶真合法,密碼相同
HttpSession session = req.getSession(true);
// 向session中添加某個屬性
session.setAttribute("pass", "ok");
// 設置超時時間。
session.setMaxInactiveInterval(20);
resp.sendRedirect("Wel?username=" + name + "&pwd=" + pwd);
} else {// 說明用戶名不存在
resp.sendRedirect("Login");
}
} else {
resp.sendRedirect("Login");
}
} catch (Exception e) {
e.printStackTrace();
resp.sendRedirect("Login");
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}