StringEscapeUtils的常用使用,防止SQL注入及XSS注入
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‘
相关推荐
ItBJLan 2020-06-11
sunlizhen 2020-04-10
sswqycbailong 2020-03-07
gwn00 2020-02-14
ALiDan 2020-07-27
qshpeng 2020-07-26
世樹 2020-07-17
chenjiazhu 2020-07-08
一对儿程序猿 2020-07-04
明月清风精进不止 2020-06-13
godfather 2020-06-13
tanrong 2020-06-11
ALiDan 2020-06-11
码墨 2020-06-09
世樹 2020-06-05
lt云飞扬gt 2020-06-03
godfather 2020-06-03