如何在 Java 中转义 HTML

本文展示了如何在Java中利用Apache Commons Text库的StringEscapeUtils.escapeHtml4()方法来转义HTML字符。通过在pom.xml文件中引入相关依赖,并在Java代码中调用该方法,可以将字符串中的HTML特殊字符转换为安全的实体。注意,从Apache Commons Lang 3.6版本开始,推荐使用Apache Commons Text,原来的StringEscapeUtils类已被弃用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在 Java 中,我们可以使用 Apachecommons-textStringEscapeUtils.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);

    }
}

输出


&lt;h1&gt; hello &amp; world&lt;/h1&gt;

注意
在过去,我们通常使用 Apachecommons-lang3StringEscapeUtils来转义 HTML,但从 3.6 开始,该类已被弃用。


// @deprecated as of 3.6, use commons-text
import org.apache.commons.lang3.StringEscapeUtils;

org.apache.commons.lang3.StringEscapeUtils is deprecated

参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值