在 Java 中,我们可以使用 Apachecommons-text来StringEscapeUtils.escapeHtml4(str)转义 HTML 字符。
pom.xml
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.8</version>
</dependency>
JavaEscapeHtmlExample.java
package com.mkyong.html;
// make sure import the correct commons-text package
import org.apache.commons.text.StringEscapeUtils;
// @deprecated as of 3.6, use commons-text StringEscapeUtils instead
//import org.apache.commons.lang3.StringEscapeUtils;
public class JavaEscapeHtmlExample {
public static void main(String[] args) {
String html = "<h1> hello & world</h1>";
String output = StringEscapeUtils.escapeHtml4(html);
System.out.println(output);
}
}
输出
<h1> hello & world</h1>
注意
在过去,我们通常使用 Apachecommons-lang3类StringEscapeUtils来转义 HTML,但从 3.6 开始,该类已被弃用。
// @deprecated as of 3.6, use commons-text
import org.apache.commons.lang3.StringEscapeUtils;
org.apache.commons.lang3.StringEscapeUtils is deprecated
本文展示了如何在Java中利用Apache Commons Text库的StringEscapeUtils.escapeHtml4()方法来转义HTML字符。通过在pom.xml文件中引入相关依赖,并在Java代码中调用该方法,可以将字符串中的HTML特殊字符转换为安全的实体。注意,从Apache Commons Lang 3.6版本开始,推荐使用Apache Commons Text,原来的StringEscapeUtils类已被弃用。

1031

被折叠的 条评论
为什么被折叠?



