package com.bjpowernode.jdbc;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Scanner;
/**
* 如果输入的用户名和密码是下面这样的,就会发生非注册人员登录的情况,叫做SQL注入现象
* 用户名:asd
* 密码:asd' or '1' = '1
*
* 输入上面的用户名和密码以后会拼接出来下面的sql语句,为此会发生SQL注入现象
* select * from t_user where login_name = 'asd' and login_pwd = 'asd' or '1' = '1' 因为这里的 1=1 恒成立
*
* 这是发生在接收用户输入,接收一行的情况下: String loginName = s.nextLine();//接收一行的输入
*
* 这是黑客使用的一种办法。
*
* 导致SQL注入的根本原因是:用户不是一般的用户,用户是懂得程序的,他输入的用户名和密码信息中含有sql语句的关键字,这些信息
* 与底层的sql语句进行了字符串的拼接,导致了原sql语句的含义被扭曲了。用户提供的信息参与了sql语
* 句的编译。(这个程序是先进行字符串的拼接,然后再进行sql语句的编译,所以才会发生注入现象)
*/
public class SQL注入现象 {
public static void main(String[] args) {
//初始化一个界面,让用户输入用户名和密码
Map<String,String> userLoginInfo = initUI();
//连接数据库验证用户名和密码是否正确
boolean ok = checkNameAndPwd(userLoginInfo.get("loginName"),userLoginInfo.get("loginPwd"));
System.out.println(ok ? "登录成功" : "登录失败");
}
/**
* 验证用户名和密码
* @param loginName 登录名
* @param loginPwd 登录密码
* @return true表示登录成功,false表示登录失败。
*/
private static boolean checkNameAndPwd(String loginName, String loginPwd) {
ResourceBundle bundle = ResourceBundle.getBundle("resources\\db");
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String user = bundle.getString("user");
String password = bundle.getString("password");
boolean ok = false;//这里准备一个boolean类型的变量,默认是false表示登录失败
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//1.注册驱动
Class.forName(driver);
//2.获取连接
conn = DriverManager.getConnection(url,user,password);
//3.获取数据库操作对象
stmt = conn.createStatement();
//4.执行SQL
String sql = "select * from t_user where login_name = '" + loginName + "' and login_pwd = '" + loginPwd + "'";
System.out.println(sql);
rs = stmt.executeQuery(sql);//程序执行到这里,才会将以上的sql语句发送到DBMS上。DBMS进行sql语句的编译
//5.处理查询结果集
if (rs.next()){
ok = true;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return ok;
}
/**
* 初始化界面,并接受用户的输入
* @return 返回存储登录名和登录密码的Map集合
*/
private static Map<String, String> initUI() {
System.out.println("欢迎使用本系统,请用户输入用户名和密码进行身份认证!");
Scanner s = new Scanner(System.in);
System.out.print("用户名:");
String loginName = s.nextLine(); //s.nextLine()是一次接收一行的输入
System.out.print("密码:");
String loginPwd = s.nextLine();
//将上面输入的用户名和密码放到Map集合中
Map<String,String> userLoginInfo = new HashMap<>();
userLoginInfo.put("loginName",loginName);
userLoginInfo.put("loginPwd",loginPwd);
//返回Map集合
return userLoginInfo;
}
}

属性配置文件db.properties在IDEA目录中所处的位置

属性配置文件db.properties中的内容



















