java字符串占位符替换与MyBatis中${}和#{}的区别

3 篇文章 0 订阅
"本文探讨了Java中三种常见的字符串占位符替换方式:`String.format()`,`MessageFormat.format()`和`StrSubstitutor.replace()`。同时,通过示例对比了MyBatis中`${}
摘要由CSDN通过智能技术生成

java字符串占位符替换

public class test {

    public static void main(String[] args) {

        String name = "张三";
        int age = 16;
        String str1 = "我叫%s,年龄%s";
        String context = String.format(str1, name, age);
        System.out.println("context: " + context);

        System.out.println("-----------------------");

        String st2 = "我叫{0},年龄{1}";
        String context2 = MessageFormat.format(st2, name, age);
        System.out.println("context2: " + context2);

        System.out.println("-----------------------");

        Map<String, String> map = new HashMap<>();
        map.put("name", "张三");
        map.put("age", "16");
        StrSubstitutor strSubstitutor = new StrSubstitutor(map);
        String str3 = "我叫${name},年龄${age}";
        String context3 = strSubstitutor.replace(str3);
        System.out.println("context3: " + context3);
    }
}

输出结果
在这里插入图片描述

MyBatis中${}和#{}的区别

1. #{}

#{}解析为一个JDBC预编译语句(prepared statement)的参数标记符,把参数部分用占位符 ? 代替。动态解析为:一个?就是一个占位符

select * from user where username = ?;
select * from user where username = #{};

在#{}预处理之后可以预防SQL注入传入username 为 a‘or’1=1,使用#{},经过sql动态解析和预编译,会把单引号转义为 ’ 那么sql最终解析为:

select * from user where username = "a\' or \'1=1 ";

转义之后因为是双引号所以sql是有问题的

2.${}

${}这种方式只会做简单的字符串替换,在动态SQL解析阶段将会进行变量替换,假如传递的参数为mini,最终处理结果如下:

select * from t_user where username = 'mini' ;

${} 预编译之前就已经被替换,有被注入的风险。如果传入的username 为 a‘or’1=1,那么使用 ${} 处理后直接替换字符串的sql就解析为:

select * from t_user where username = 'a' or '1=1' ;
select * from t_user where username = ${} ;

这样sql就是一个正常的sql语句了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

罗小稳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值