Files
shz-backend/ruoyi-bussiness/src/main/java/com/ruoyi/cms/util/RichTextSanitizer.java
lapuda c1a7aa3532 feat: Add news information management module with API and database support
- Introduced new API endpoints for querying and managing news information in the CMS.
- Implemented data model for NewsInfo and NewsInfoQuery with validation.
- Created NewsInfoMapper for database interactions and corresponding XML mappings.
- Developed INewsInfoService interface and its implementation for business logic.
- Added RichTextSanitizer utility for cleaning HTML content to prevent XSS attacks.
- Created unit tests for RichTextSanitizer to ensure proper functionality.
- Updated database schema with news_info table and necessary fields, including status and module.
- Added migration scripts for setting up the news information module in the database.
- Integrated jsoup library for HTML sanitization.
2026-07-20 14:54:15 +08:00

50 lines
1.6 KiB
Java

package com.ruoyi.cms.util;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Safelist;
/**
* 富文本 HTML 白名单清理。
*
* <p>保留新闻正文所需的常见排版、链接、图片和表格标签,移除脚本、事件属性、
* iframe 以及 javascript/data 等危险协议。</p>
*/
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();
}
}