MyBatis如何防止SQL注入

SQL注入

什么是SQL注入呢?首先SQL注入是一种攻击手段,一种使用构造恶意的SQL语句,欺骗服务器执行SQL命令,让后台的数据库去解析,从而达到入侵目标网络,获取敏感信息的攻击手段。

MyBatis如何防止SQL注入

SQL中#和$区别
#$
相当于对数据加上双引号相当于直接显示数据
很大程度上防止SQL注入无法防止SQL注入
#{xxx},使用的是PreparedStatement,会有类型转换,比较安全${xxx},使用字符串拼接,容易SQL注入

 简单的说就是#{}是经过预编译的,是安全的,${}是未经过预编译的,仅仅是取变量的值,是非安全的,存在SQL注入。

例子

 1 <select id="selectBackGoodsDetail" resultType="java.util.Map">
 2     SELECT sum(a.item_num) backGoodsNum,a.item_price backGoodsPrice,
 3     sum(a.item_num * a.item_price) backGoodsSumPrice,
 4     b.barcode,b.name itemName,b.weight,c.name itemCategoryName
 5     FROM back_goods_detail a
 6     LEFT JOIN item b ON a.item_id=b.id
 7     LEFT JOIN item_category c ON b.item_category_id =c.id
 8     <where>
 9         <if test="backGoodsId!=null">
10             a.back_goods_id = #{backGoodsId}
11         </if>
12         <if test="itemCategoryId!=null">
13             AND b.item_category_id = #{itemCategoryId}
14         </if>
15         <if test="searchKey!= null">
16             AND (b.sequence LIKE CONCAT('%', #{searchKey}, '%')
17             OR b.name LIKE CONCAT('%', #{searchKey}, '%')
18             OR b.barcode LIKE CONCAT('%',#{searchKey},'%'))
19         </if>
20     </where>
21     GROUP BY a.item_id
22     LIMIT #{pageStart},#{pageNum}
23 </select>

转载于:https://www.cnblogs.com/PreachChen/p/9103278.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis 有以下几种方法来防止 SQL 注入: 1. 使用参数化查询 MyBatis 推荐使用参数化查询来防止 SQL 注入。参数化查询使用 ? 或者 #{param} 来表示占位符,然后使用 PreparedStatement 进行预编译,将参数设置到占位符中,最后执行查询操作。这种方式可以避免用户输入的参数直接拼接到 SQL 语句中,从而防止 SQL 注入攻击。 示例: ``` <select id="getUserById" parameterType="int" resultType="User"> SELECT * FROM user WHERE id = #{id} </select> ``` 2. 使用动态 SQL MyBatis 的动态 SQL 可以根据条件动态生成 SQL 语句,避免拼接 SQL 语句时产生 SQL 注入漏洞。MyBatis 提供了多种动态 SQL 标签,如 if、choose、when、otherwise、foreach、set、trim、where、sql 等。 示例: ``` <select id="getUserList" parameterType="Map" resultType="User"> SELECT * FROM user <where> <if test="name != null and name != ''"> AND name = #{name} </if> <if test="age != null"> AND age = #{age} </if> </where> </select> ``` 3. 使用 SQL 注入过滤器 MyBatis 可以通过插件来实现 SQL 注入过滤器,对于输入的参数进行过滤和转义,确保参数不会被注入到 SQL 语句中。 示例: ``` public class SqlInjectionPlugin implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); for (int i = 0; i < args.length; i++) { if (args[i] instanceof String) { args[i] = sqlInjectionFilter((String) args[i]); } } return invocation.proceed(); } private String sqlInjectionFilter(String param) { // 进行参数过滤和转义 return param; } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { // 配置属性 } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值