Java代码中如何转义HTML呢?

乔欣 Java经验 发布时间:2023-01-28 14:55:46 阅读数:18850 1
下文笔者讲述java代码中对html字符进行转义的方法分享,如下所示
html字符转义的实现思路
      引入Apache commons-text jar包
	  然后使用其中的StringEscapeUtils.escapeHtml4(str)即可对HTML字符进行转义
例:
html字符转义的示例
pom.xml
一、引入依赖

<dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-text</artifactId>
      <version>1.8</version>
  </dependency>


JavaEscapeHtmlExample.java

二、编写相应的html字符转义代码

package com.java265.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  java265.com java爱好者</h1>";
        String output = StringEscapeUtils.escapeHtml4(html);
        System.out.println(output);
    }
}
-----运行以上代码,将输出以下信息----
<h1> hello  java265.com java爱好者</h1>
注意事项:
    从Apache commons-lang3的3.6版本后官方不推荐使用此类
    // @deprecated as of 3.6, use commons-text
    import org.apache.commons.lang3.StringEscapeUtils;
    org.apache.commons.lang3.StringEscapeUtils is deprecated
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202301/16748889975551.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者