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>
https://www.cnblogs.com/baby123/p/11462889.html