我正在寻找一种 html 清理器,我可以根据 API 调用它来清理从我的 web 应用程序中获取的字符串。是否有一些有用且易于使用的库可用?有人知道一两个吗?
我不需要太大的东西,它只需要能够找到未关闭的标签并关闭它们即可。
最佳答案
https://github.com/OWASP/java-html-sanitizer现在已标记为可供生产使用。
A fast and easy to configure HTML Sanitizer written in Java which lets you include HTML authored by third-parties in your web application while protecting against XSS.
您可以使用 prepackaged policies
Sanitizers.FORMATTING.and(Sanitizers.LINKS)
或 tests展示如何轻松配置自己的:
new HtmlPolicyBuilder()
.allowElements("a")
.allowUrlProtocols("https")
.allowAttributes("href").onElements("a")
.requireRelNofollowOnLinks()
或编写自定义策略来执行某些操作,例如将 h1
更改为具有特定类的 div
:
new HtmlPolicyBuilder()
.allowElements("h1", "p")
.allowElements(
new ElementPolicy() {
public String apply(String elementName, List<String> attrs) {
attrs.add("class");
attrs.add("header-" + elementName);
return "div";
}
}, "h1"))
关于java - 用于 HTML 清理的库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1947021/