import org.jsoup.Jsoup;
public static String sanitizeHtml(String input) {
// 使用 Jsoup 消毒 HTML
return Jsoup.clean(input, Safelist.relaxed());
}
public static void main(String[] args) {
String userInput = "<p><script>alert(1)</script>Safe Content</p>";
String sanitizedHtml = sanitizeHtml(userInput);
System.out.println(sanitizedHtml);
}
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.14.3</version> <!-- 使用最新版本 -->
</dependency>
结果:
另外一种可以script里面的字段也可以提出来
https://github.com/finn-no/xss-html-filter 依赖自行导入本地库
public static void main(String[] args) {
String input = "<p><script>alert(1)</script>Safe Content</p>";
String clean = new HTMLFilter().filter( input );
System.out.println(clean);
}
结果为: