天天看点

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);
        }
    }