JDBC-用户登录验证(sql注入)
需求:实现用户登录功能
描述:提供一个登陆的入口,可以让用户输入用户名和密码,提交信息后,java程序收集用户信息,
java程序连接数据库,校验用户名和密码
这种方式会有漏洞存在,导致sql注入;导致sql注入的根本原因是用户输入含有sql语句关键字,
并且这些关键字参与了sql语句的编译过程,导致sql语句原意被扭曲,进而达到sql注入
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.sql.*;
public class JdbcTest06 {
public static void main(String[] args) {
//1.初始化界面,创建Map集合接收用户名和密码
Map<String,String> userInfo = initUI();
//2.通过loginSuccess的值判断登陆成功与否
boolean loginSuccess = login(userInfo);
System.out.println(loginSuccess ? "登陆成功":"登陆失败");
}
private static boolean login(Map<String, String> userInfo) {
boolean loginSuccess = false;
Connection con = null;
Statement state = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/firstbase", "root", "123456");
state = con.createStatement();
String userName = userInfo.get("userName");
String password = userInfo.get("password");
// 这种方式会有漏洞存在,导致sql注入;导致sql注入的根本原因是用户输入含有sql语句关键字,
// 并且这些关键字参与了sql语句的编译过程,导致sql语句原意被扭曲,进而达到sql注入
String sql = "select * from t_users where username = '"+ userName +"' and password = '"+ password +"'";
rs = state.executeQuery(sql);
if (rs.next()){
loginSuccess = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return loginSuccess;
}
private static Map<String,String> initUI() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String userName = sc.nextLine();
System.out.println("请输入密码:");
String password = sc.nextLine();
Map<String, String> userInfo = new HashMap<>();
userInfo.put("userName", userName);
userInfo.put("password", password);
return userInfo;
}
}
When nothing seems to help, I go look at a stonecutter hammering away at his rock, perhaps a hundred times without as much as a crack showing in it. Yet at the hundred and first blow it will split in two, and I know it was not that blow that did it, but all that had gone before. -- Jacob Riis