1. 程式人生 > 資料庫 >Mybatis之預防SQL注入攻擊

Mybatis之預防SQL注入攻擊

文章目錄

1. 什麼是SQL注入攻擊

sql注入是指攻擊者利用SQL漏洞,繞過系統約束,越權獲取資料的攻擊方式

2. MyBatis兩種傳值方式

  1. ${} 文字替換,未經任何處理對SQL文字替換
  2. #{} 預編譯傳值,使用預編譯傳值可以預防SQL注入

3. ${} 方式的問題

goods.xml檔案中

<select id="selectByTitle" parameterType="java.util.Map" resultType="com.mybatis.entity.Goods">
        select * from t_goods where title =${title}
    </select>
@Test
    public void testSelectByTitle() throws Exception {
        SqlSession session = null;
        try{
            session = MyBatisUtils.openSession();
            Map map = new HashMap();
            map.put("title", "''or 1=1 or title ='100'");

            List<Goods> g = session.selectList("goods.selectByTitle", map);
            for(Goods f: g){
                System.out.println(f.getTitle() + "\t" + f.getCurrentPrice());
            }

        }catch(Exception e){
            throw e;
        }finally{
            MyBatisUtils.closeSession(session);
        }
    }

結果會出現所有資料
在這裡插入圖片描述
就產生了sql注入問題

4. #{} 方式

<select id="selectByTitle" parameterType="java.util.Map" resultType="com.mybatis.entity.Goods">
        select * from t_goods where title =#{title}
    </select>
 @Test
    public void testSelectByTitle() throws Exception {
        SqlSession session = null;
        try{
            session = MyBatisUtils.openSession();
            Map map = new HashMap();
            map.put("title", "''or 1=1 or title ='100'");

            List<Goods> g = session.selectList("goods.selectByTitle", map);
            for(Goods f: g){
                System.out.println(f.getTitle() + "\t" + f.getCurrentPrice());
            }

        }catch(Exception e){
            throw e;
        }finally{
            MyBatisUtils.closeSession(session);
        }
    }

結果沒有任何結果
在這裡插入圖片描述