使用Jsoup防止富文本Xss攻击

Jsoup Github地址,官网地址

添加maven依赖

<dependency>
  <!-- jsoup HTML parser library @ https://jsoup.org/ -->
  <groupId>org.jsoup</groupId>
  <artifactId>jsoup</artifactId>
  <version>1.13.1</version>
</dependency>

测试代码

官方示例代码地址

public static void main(String[] args) {
	String content = "<h1><span onclick=\"alert('测试')\" style=\"background-color: rgb(194, 79, 74); font-style: italic; color: rgb(139, 170, 74);\">测试XSS</span></h1>";
	Whitelist whitelist = new Whitelist();
       // 具体标签和属性设置根据实际情况配置
	whitelist.addAttributes(":all","style","title","font-style");
	whitelist.addTags("p","h1","div","span");
	String result = Jsoup.clean(content, whitelist);
	System.out.println(result);//<h1><span style="background-color: rgb(194, 79, 74); font-style: italic; color: rgb(139, 170, 74);">测试XSS</span></h1>
}