package com.ruoyi.cms.util; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.safety.Safelist; /** * 富文本 HTML 白名单清理。 * *

保留新闻正文所需的常见排版、链接、图片和表格标签,移除脚本、事件属性、 * iframe 以及 javascript/data 等危险协议。

*/ public final class RichTextSanitizer { private static final Safelist NEWS_CONTENT_SAFELIST = Safelist.relaxed() .addTags("figure", "figcaption", "s") .addAttributes("a", "target", "rel") .addAttributes("img", "loading") .addAttributes("table", "border", "cellpadding", "cellspacing") .addProtocols("a", "href", "http", "https", "mailto") .addProtocols("img", "src", "http", "https"); private static final Document.OutputSettings OUTPUT_SETTINGS = new Document.OutputSettings() .prettyPrint(false); private RichTextSanitizer() { } /** * 清理并规范化富文本 HTML。 */ public static String clean(String html) { if (html == null) { return null; } return Jsoup.clean(html, "", NEWS_CONTENT_SAFELIST, OUTPUT_SETTINGS).trim(); } /** * 判断清理后的正文是否包含文字或图片内容。 */ public static boolean hasContent(String cleanedHtml) { if (cleanedHtml == null || cleanedHtml.trim().isEmpty()) { return false; } Document document = Jsoup.parseBodyFragment(cleanedHtml); return !document.text().trim().isEmpty() || !document.select("img").isEmpty(); } }