标签:stringbu copy sql where ons bar use 用户 com
StringEscapeUtils类可以对html js xml sql 等代码进行转义来防止SQL注入及XSS注入
添加依赖
<dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency>
1.html脚本
escapeHtml转义html脚本
unescapeHtml反转义html脚本
System.out.println(StringEscapeUtils.escapeHtml("<a>abc</a>")); System.out.println(StringEscapeUtils.unescapeHtml("<a>abc</a>"));
输出
<a>abc</a>
<a>abc</a>
2.js脚本
escapeJavaScript转义js脚本
unescapeJavaScript反转义js脚本
System.out.println(StringEscapeUtils.escapeJavaScript("<script>alert(‘123‘)<script>")); System.out.println(StringEscapeUtils.unescapeJavaScript("<script>alert(\‘123\‘)<script>"));
输出
<script>alert(\‘123\‘)<script>
<script>alert(‘123‘)<script>
3.字符串Unicode
escapeJava转义成Unicode编码
unescapeJava反转义成Unicode编码
System.out.println(StringEscapeUtils.escapeJava("你好")); System.out.println(StringEscapeUtils.unescapeJava("\u4F60\u597D"));
输出
\u4F60\u597D
你好
4.xml
escapeXML转义XML
unescapeXML反转义XML
System.out.println(StringEscapeUtils.escapeXml("<name>贝贝</name>")); System.out.println(StringEscapeUtils.unescapeXml("<name>贝贝</name>"));
输出
<name>贝贝</name>
<name>贝贝</name>
5.sql
escapeSql sql转义,防止sql注入攻击
转义后
StringBuffer sql = new StringBuffer("select * from users where 1=1 "); String keyWord="aaa‘ or ‘1=1"; if(!keyWord.isEmpty()){ sql.append(" and username like ‘%" + StringEscapeUtils.escapeSql(keyWord) + "‘"); } System.out.println(sql);
输出
select * from users where 1=1 and username like ‘%aaa‘‘ or ‘‘1=1‘
StringEscapeUtils.escapeSql会将1个‘转成2个‘,附源码:
不进行转义的,会查出全部用户
select * from users where 1=1 and username like ‘%aaa‘ or ‘1=1‘
StringEscapeUtils的常用使用,防止SQL注入及XSS注入
标签:stringbu copy sql where ons bar use 用户 com
原文地址:https://www.cnblogs.com/651434092qq/p/12427323.html