场景

  1. 在开发Java Web程序时,为了防止XSSJavaScript攻击, 需要对用户输入转义,使JavaScript脚本不能执行. 在前端可以通过获取<div>innerHTML属性来获取转义内容,但是在服务端如何进行转义?因为客户端是可以绕过的.

说明

  1. HTML内容的转义在开发Web时肯定是必须做的,在入数据库之前得转义,而不是在用的时候再转义。主要是防止在使用这类数据的时候忘记没有转义导致的XSS安全问题.

  2. 转义HTML字符主要涉及到5个字符<>"'&,所以只需要转义这几个即可。要实现转义字符,最基本的做法就是通过逐个分析String里的字符,之后使用转移字符串替换. 看htmlEscape1()方法即是最基本的做法。而另一种做法就是使用htmlEscape2(),它之前讲过的使用正则高效替换字符串的多个占位符为多个值[3]. 这两种方法在进行测试执行时间的时候方法1更快,可见正则匹配更耗费时间。

输出

package com.example.string;import static org.junit.jupiter.api.Assertions.assertEquals;import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;import org.junit.jupiter.api.Test;public class HtmlEscapeTest{public static String htmlEscape1(String str) {if(isEmpty(str))return str;StringBuilder w = new StringBuilder();for (int i = 0, len = str.length(); i < len; i++) {char cur = str.charAt(i);switch (cur) {case '<':w.append("&lt;");break;case '>':w.append("&gt;");break;case '"':w.append("&quot;");break;case '\'':w.append("'");break;case '&':w.append("&amp;");break;default:w.append(cur);break;}}return w.toString();}private static boolean isEmpty(String str) {return str == null || str.isEmpty();}/**** StringBuilder sb = new StringBuilder();* HashMap<String, String> oldToNew = new HashMap<>();* oldToNew.put("$sn",sn);* oldToNew.put("$email",mail);* StringUtils.replaceOneMore(sb,registertemplate,"[$]sn|[$]email",oldToNew);** @param output* @param input* @param oldRegex* @param oldToNew*/public static void replaceOneMore(StringBuilder output, String input,String oldRegex, Map<String,String> oldToNew){Pattern p = Pattern.compile(oldRegex);Matcher m = p.matcher(input);while (m.find()) {String one = m.group();if(oldToNew.containsKey(one))m.appendReplacement(output, oldToNew.get(one));}m.appendTail(output);}public static String htmlEscape2(String source){if(isEmpty(source))return source;StringBuilder builder = new StringBuilder();HashMap<String, String> oldToNew = new HashMap<>();oldToNew.put("<","&lt;");oldToNew.put(">","&gt;");oldToNew.put("\"","&quot;");oldToNew.put("'","'");oldToNew.put("&","&amp;");long start2 = System.currentTimeMillis();replaceOneMore(builder,source,"[<]|[>]|[\"]|[']|[&]",oldToNew);    long end2 = System.currentTimeMillis();print("replaceOneMore",end2-start2);return builder.toString();    }public static String htmlUnescape(String str){if(isEmpty(str))return str;if(str.indexOf("&") == -1)return str;StringBuilder sb = new StringBuilder();HashMap<String, String> oldToNew = new HashMap<>();oldToNew.put("&lt;","<");oldToNew.put("&gt;",">");oldToNew.put("&quot;","\"");oldToNew.put("'","\'");oldToNew.put("&amp;","&");replaceOneMore(sb,str,"[&]lt;|[&]gt;|[&]quot;|[&]#39;|[&]amp;",oldToNew);return sb.toString();  }public static<T> void print(String key,T t){System.out.println(key +" : "+t);}@Testpublic void testEscapeHtml(){String str = "<a href=\"http://blog.csdn.net/infoworld?name=tobey&year=2021\"></a><script>alert('hello')</script>&"+"<a href=\"http://blog.csdn.net/infoworld?name=tobey&year=2021\"></a><script>alert('hello')</script>&"+"<a href=\"http://blog.csdn.net/infoworld?name=tobey&year=2021\"></a><script>alert('hello')</script>&"+"<a href=\"http://blog.csdn.net/infoworld?name=tobey&year=2021\"></a><script>alert('hello')</script>&"+"<a href=\"http://blog.csdn.net/infoworld?name=tobey&year=2021\"></a><script>alert('hello')</script>&"+"<a href=\"http://blog.csdn.net/infoworld?name=tobey&year=2021\"></a><script>alert('hello')</script>&"+"<a href=\"http://blog.csdn.net/infoworld?name=tobey&year=2021\"></a><script>alert('hello')</script>&"+"<a href=\"http://blog.csdn.net/infoworld?name=tobey&year=2021\"></a><script>alert('hello')</script>&"+"<a href=\"http://blog.csdn.net/infoworld?name=tobey&year=2021\"></a><script>alert('hello')</script>&"+"<a href=\"http://blog.csdn.net/infoworld?name=tobey&year=2021\"></a><script>alert('hello')</script>&";long start1 = System.currentTimeMillis();String result1 = htmlEscape1(str);long old1 = System.currentTimeMillis();print("result1",result1);print("duration",old1-start1);long start2 = System.currentTimeMillis();String result2 = htmlEscape2(str);long end2 = System.currentTimeMillis();print("result2",result2);print("duration",end2-start2);assertEquals(result2, result1);String source = htmlUnescape(result2);assertEquals(source, str);print("source",source);}
}

输出

result1 : &lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;
duration : 1
replaceOneMore : 8
result2 : &lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;&lt;a href=&quot;http://blog.csdn.net/infoworld?name=tobey&amp;year=2021&quot;&gt;&lt;/a&gt;&lt;script&gt;alert('hello')&lt;/script&gt;&amp;
duration : 8
source : <a href="http://blog.csdn.net/infoworld?name=tobey&year=2021"></a><script>alert('hello')</script>&<a href="http://blog.csdn.net/infoworld?name=tobey&year=2021"></a><script>alert('hello')</script>&<a href="http://blog.csdn.net/infoworld?name=tobey&year=2021"></a><script>alert('hello')</script>&<a href="http://blog.csdn.net/infoworld?name=tobey&year=2021"></a><script>alert('hello')</script>&<a href="http://blog.csdn.net/infoworld?name=tobey&year=2021"></a><script>alert('hello')</script>&<a href="http://blog.csdn.net/infoworld?name=tobey&year=2021"></a><script>alert('hello')</script>&<a href="http://blog.csdn.net/infoworld?name=tobey&year=2021"></a><script>alert('hello')</script>&<a href="http://blog.csdn.net/infoworld?name=tobey&year=2021"></a><script>alert('hello')</script>&<a href="http://blog.csdn.net/infoworld?name=tobey&year=2021"></a><script>alert('hello')</script>&<a href="http://blog.csdn.net/infoworld?name=tobey&year=2021"></a><script>alert('hello')</script>&

参考

  1. Java escape HTML - Stack Overflow

  2. Why to Encode (escape) Special Characters in HTML

  3. 使用正则高效替换字符串的多个占位符为多个值

[JavaWeb]_[初级]_[对Html特殊符号进行转义防止XSS攻击和反转义]相关推荐

  1. [JavaWeb]_[初级]_[如何更换免费网站字体]

    场景 在开发Web网站时, 标准字体比较难看,这时候可以更换免费的Web字体来美化网页.Windows系统自带的字体大多数都是商业字体,只能在Windows上使用,不可以用于商业运行.目前国内有免费商 ...

  2. [Java]_[初级]_[使用正则高效替换字符串的多个占位符为多个值]

    场景 在开发基于模板内容的Java程序时, 比如一个邮件内容模板,在内容里放置一些占位符$email,$name等来作为替换实际内容的符号.那么这时候如何做才可以少生成不必要的String字符串,从而 ...

  3. [WTL/ATL]_[初级]_[微调控件CUpDownCtrl的使用]

    场景 开发WTL/ATL应用时,有时候需要对某些值进行微调,比如0-100的百分比的微调,或者字号的微调,通过键盘操作微调控件,能实时查看某些界面呈现的效果.而WTL提供了CUpDownCtrl控件, ...

  4. [Android]_[初级]_[sdk docs reference api 文档打开慢的解决办法]

    此题正解:打开firefox, 选中菜单 File->Work Offline,之后打开api文档都是秒开了,缺点就是不能访问在线的网址. 默认菜单是隐藏的,可以移动到Tab页空白处右键Menu ...

  5. [C/C++标准库]_[初级]_[优先队列priority_queue的使用]

    2019独角兽企业重金招聘Python工程师标准>>> std::priority_queue 场景: 1. 对于一个任务队列,任务的优先级由任务的priority属性指明,这时候就 ...

  6. [C/C++11]_[初级]_[如何转换带井号的#十六进制颜色字符串到数值]

    场景 表示颜色的RGB值,一般有两种方法,一种是使用使用数值表示RGB(255,255,255),一种是使用字符串#FE07AB.那么字符串形式的表示如何得到r,g,b各值的数值大小呢? 说明 在&l ...

  7. [Python]_[初级]_[使用PyCharm时不识别根包位置和Debug时报ModuleNotFoundError错误]

    场景 在使用PyCharm开发程序时,当我们Debug某个文件时,会报以下错误,什么原因? Traceback (most recent call last):File "C:\Progra ...

  8. [macOS]_[初级]_[关于程序签名时出现User interaction is not allowed的问题]

    场景 当做macOS的程序做持续集成时, 服务器上自动构建的项目在构建完之后需要签名, 这时候在签名时出现User interaction is not allowed 错误, 导致签名失败, 从而程 ...

  9. [C++11]_[初级]_[十六进制字符串转换为字节数组]

    场景 在开发使用加密算法md5,sha256等的功能时, 会生成基于十六进制的字符串密钥. 这时候在使用这些密钥进行解密或加密的时候,第三方库都需要传入一个字节数组usigned char*格式的数组 ...

最新文章

  1. 海量数据处理——位图法bitmap
  2. 程序猿要什么爱情,陪你未来的是键盘和代码啊!
  3. 深度学习数据扩张_适用于少量数据的深度学习结构
  4. python整数运算_深入 Python (6) 整数对象的数学运算
  5. 超仪电子 java面试_全靠这份阿里大佬的“Java进阶面试手册”助我收获蚂蚁金服offer!...
  6. Oracle EBS学习网站列表
  7. 互联网下一个热点:服务业电子商务
  8. 关于Lua的下载以及wlua、luac等文件的解释
  9. 2022年最新的西安Java培训机构十大排名榜单
  10. PMP第三节:项目管理过程
  11. 视频教程-大数据与数据仓库入门到精通-Hadoop
  12. 什么是零代码开发平台,为什么企业IT应该重视?
  13. unity3d 压缩文件夹和压缩文件
  14. Codeforces 1635 E. Cars 二分图+拓扑排序
  15. 行锁、间隙锁、next-key锁
  16. 关于谱图理论-图傅里叶变换-谱卷积等谱图领域知识的理解
  17. CVPR 2022 | 数据堂亮相计算机视觉领域盛会
  18. mysql在 union 与group by后order by排序混乱
  19. 计算机安全技术 实验报告,网络安全技术实验报告(共10篇).doc
  20. vue项目中npm install安装失败,万能解决方法

热门文章

  1. PK656个对手!深兰科技在全球顶级AI赛事kaggle竞赛中再次夺冠
  2. Java时间对比compareTo用法
  3. 基于GRNN广义回归神经网络的车牌字符分割和识别matlab仿真
  4. 微信群裂变操作流程方案
  5. 三篇ICLR2022与时间图序列相关的研究工作
  6. 轻松实现全国高校地理位置数据爬取
  7. 基于jquery.jsPlumb编写拓扑图
  8. 数据结构:链表(Linklist)的定义和它的函数们
  9. 深度学习未来的发展点
  10. 电脑飞车,qq飞车电脑版