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语句了