Java代码中如何转义HTML呢?
下文笔者讲述java代码中对html字符进行转义的方法分享,如下所示
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
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。