6. 使用 JDBC 完成登录案例 以及 SQL 注入问题

6. 使用 JDBC 完成登录案例 以及 SQL 注入问题

前言

在前面的章节中,我们已经学会了使用 statement 来执行数据库的 增删查改 的操作,并且封装一个 JDBC 工具类,实现了数据库连接获取,以及资源关闭的方法。

下面我们来使用 statement 来实现一个简单的用户登录案例,并且引出一个 SQL 注入的问题。

案例-登录案例

1.需求

在控制台输入用户名和密码,查询数据库,如果数据库存在当前用户,显示登录成功!

如果数据库不存在当前用户,显示登录失败!

6. 使用 JDBC 完成登录案例 以及 SQL 注入问题
img

2分析

2.1登录是做什么

  • 登录说白了就是根据用户名和密码查询数据库, 如果能查询出来就是登录成功, 查询不出来就是登录失败

2.2思路分析

6. 使用 JDBC 完成登录案例 以及 SQL 注入问题
image-20191202144713867

3.代码实现

3.1 那么首先我们需要准备前面篇章生成的 MySQL 数据,如下:

mysql> select * from t_user;
+----+-------+------+------+
| id | uname | age  | sex  |
+----+-------+------+------+
|  1 | zs    |   18 |    1 |
|  2 | ls    |   20 |    0 |
|  3 | ww    |   23 |    1 |
|  4 | zl    |   24 |    1 |
|  5 | lq    |   15 |    0 |
|  6 | hh    |   12 |    0 |
|  7 | wzx   |   60 | NULL |
|  8 | lb    | NULL | NULL |
+----+-------+------+------+
8 rows in set (0.00 sec)

mysql> 

3.2 准备上一篇章封装好的 JdbcUtil 工具类

  • 创建配置文件,配置文件在resources目录下,并且要将resources目录标记为资源文件的根路径,扩展名是properties
6. 使用 JDBC 完成登录案例 以及 SQL 注入问题
1537261759376

配置文件:

jdbc.username=root
jdbc.password=Li********密码**********0
jdbc.url=jdbc:mysql://localhost:3306/testdb?rewriteBatchedStatements=true&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.driverClass=com.mysql.jdbc.Driver


  • 工具类如下:
6. 使用 JDBC 完成登录案例 以及 SQL 注入问题
image-20210121000203107
package com.utils;

import Java.io.InputStream;
import java.sql.*;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 *
 * @Description:JdbcUtils 工具类
 * 1.抽取: 复用重复的代码
 *      方式: 把重复代码抽取到父类, 把公共代码抽取成方法, 把公共代码抽取到工具类
 *      原则: 抽取重复的
 * 2.选择把公共代码抽取到工具类
 *      找重复的: (1,2 -- 获得连接的方法), (5-- 释放资源的方法)
 *   思路:
 *      定义一个类
 *      在这个类里面定义两个方法
 * 3. 工具类优化
 *      把四个参数(驱动,路径,用户名,密码)抽取成 jdbc.properties
 *      在static{}里面读取jdbc.properties, 给变量赋值
 *
 * @author Aron.li
 * @date 2021/1/20 7:59
 */

public class JdbcUtils {

    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;

    //驱动只需要注册一次,把注册驱动的代码放在静态代码块
    static {
        //静态代码块就会在类加载的时候执行
        try {
            //读取jdbc.properties配置文件中的内容
            //1. 将配置文件转换成字节输入流,使用类加载器
            InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            //2. 创建一个Properties对象
            Properties properties = new Properties();
            //3. properties对象加载配置文件
            properties.load(is);

            //4.调用properties的方法,根据key获取值
            username = properties.getProperty("jdbc.username");
            password = properties.getProperty("jdbc.password");
            url = properties.getProperty("jdbc.url");
            driverClass = properties.getProperty("jdbc.driverClass");

            //5.注册驱动
            Class.forName(driverClass);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获得连接
     *
     */

    public static Connection getConnection() {
        //2. 获得连接
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage()); // 抛出运行时异常
        }
        return connection;
    }

    /**
     * 释放资源
     *
     * @param resultSet
     * @param statement
     * @param connection
     */

    public static void closeAll(ResultSet resultSet, Statement statement, Connection connection) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }

            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage()); // 抛出运行时异常
        }

    }

    public static void closeAll(Statement statement, Connection connection) throws SQLException {
        closeAll(null, statement, connection);
    }

}

3.3 创建登录测试类 LoginClient

6. 使用 JDBC 完成登录案例 以及 SQL 注入问题
image-20210121001514776
public class LoginClient {

    /**
     * 使用 JDBC 实现登录案例
     */

    public static void main(String[] args) throws SQLException {

        //1. 获取用户输入的 用户名
        System.out.println("请输入的用户名: ");
        Scanner scanner = new Scanner(System.in);
        String username = scanner.nextLine();
        System.out.println("输入的用户名: " + username);

        //2. 获取数据库连接
        Connection connection = JdbcUtils.getConnection();

        //3. 根据用户名执行数据查询
        String sql = "select * from t_user where uname = '" + username + "'"// 设置SQL
        Statement statement = connection.createStatement(); // 获取statement
        ResultSet resultSet = statement.executeQuery(sql); // 执行查询SQL

        //4. 如果查询存在用户名的数据,那么则登录成功;反之,登录失败
        if (resultSet.next()) {
            System.out.println("登录成功");
        } else {
            System.out.println("登录失败");
        }
    }

}

3.4 执行测试登录如下:

6. 使用 JDBC 完成登录案例 以及 SQL 注入问题

4.小结

4.1登录思路

  • 登录说白了就是根据用户名和密码查询数据库
  • 登录思路
    • 登录成功 打印 ‘登录成功’
    • 登录失败 打印 登录失败’
    • 获得用户输入的用户名和密码
    • 使用Jdbc根据用户名和密码查询数据库 封装成User对象
    • 判断是否登录成功(判断User是否为null)

5.使用 statement 执行SQL,则会出现 SQL 注入的问题

5.1 SQL注入问题出现

当输入的密码  ' or '' = ' , 发现永远登录成功.

  • 下面我们首先演示查询一个不存在的用户名,登录失败的情况,如下:

6. 使用 JDBC 完成登录案例 以及 SQL 注入问题

  • 然后拼接 ' or '' = ' 字符串,将会登录成功

6. 使用 JDBC 完成登录案例 以及 SQL 注入问题

5.2 SQL注入问题分析

  • 输入的密码  ‘ or ” = ‘, 语句如下
-- 当查询 hello 的用户名,则会查询无数据
mysql> select * from t_user where uname = 'hello';
Empty set (0.00 sec)
-- 当在查询条件后面加上 or '' = '' ,那么则可以查询出所有数据
mysql> select * from t_user where uname = 'hello' or '' = '';
+----+-------+------+------+
| id | uname | age  | sex  |
+----+-------+------+------+
|  1 | zs    |   18 |    1 |
|  2 | ls    |   20 |    0 |
|  3 | ww    |   23 |    1 |
|  4 | zl    |   24 |    1 |
|  5 | lq    |   15 |    0 |
|  6 | hh    |   12 |    0 |
|  7 | wzx   |   60 | NULL |
|  8 | lb    | NULL | NULL |
+----+-------+------+------+
8 rows in set (0.00 sec)

mysql> 

相似会出现问题的SQL 如下:

select * from t_user where uname = 'hello' or '' = '';
select * from t_user where uname = 'hello' or true;
select * from t_user where  true;
select * from t_user;
  • 发现语句出现了sql注入问题

    这是因为 statement 在使用拼接 sql 字符串的时候, 把用户输入的 or 当成关键词注入到了sql语句里面了。

    那么该怎么解决这个问题呢?我们将会在下一个章节,使用 preparedStatement 解决 SQL 注入的问题。


原文始发于微信公众号(海洋的渔夫):6. 使用 JDBC 完成登录案例 以及 SQL 注入问题

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/33932.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!