天天看點

016.Mybatis預防SQL注入攻擊

1.Sql注入是什麼

 2.倆種傳值方式

016.Mybatis預防SQL注入攻擊

 3.相關語句(進階查詢必須要進行sql拼接時用$,如${order},但絕對不能讓使用者從前台輸入)

<select id="selectByTitle" parameterType="java.util.Map" resultType="com.imooc.mybatis.entity.Goods">
        select *
        from t_goods
        where title = #{title} ${order}
    </select>      
/**
     * 預防SQL注入
     *
     * @throws Exception
     */
    @Test
    public void testSelectByTitle() throws Exception
    {
        SqlSession session = null;
        try
        {
            session = MyBatisUtils.openSession();
            Map param = new HashMap();
            /*
                ${}原文傳值
                select * from t_goods
                where title = '' or 1 =1 or title = '【德國】愛他美嬰幼兒配方奶粉1段800g*2罐 鉑金版'
            */
            /*
               #{}預編譯
               select * from t_goods
                where title = "'' or 1 =1 or title = '【德國】愛他美嬰幼兒配方奶粉1段800g*2罐 鉑金版'"
            */

            param.put("title", "'' or 1=1 or title='斯利安 孕媽專用 洗髮乳 氨基酸表面活性劑 舒緩頭皮 滋養發根 讓你的秀發會喝水 品質孕媽'");
            param.put("order", " order by title desc");
            List<Goods> list = session.selectList("goods.selectByTitle", param);
            for (Goods g : list)
            {
                System.out.println(g.getTitle() + ":" + g.getCurrentPrice());
            }
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            MyBatisUtils.closeSession(session);
        }
    }