java实现HTML标签转义和反转义(StringEscapeUtils)

转义:有时需要对带有格式的长文本(如个人文章或评论等)进行转义后存储到数据库表中。

      例如:String EsHtml="<p>我的<br/>评论</p>";

                 转义后为"&lt;p&gt;我的&lt;br/&gt;评论&lt;/p&gt"

反转义:数据库中存储的转义后的文本有时需要反转至页面。

      例如:字符串: "&lt;p&gt;我的&lt;br/&gt;评论&lt;/p&gt"

                 反转义后为"<p>我的<br/>评论</p>"

        在apache的工具包common-lang中有StringEscapeUtils工具类,可以对HTML标签进行转义和反转义,但是该工具类的转义方法escapeHtml对于中文字符兼容性不是很好,因此需要自定义方法对特殊字符进行处理。

1、HTML标签转义:

      public class test {
      public static void main(String[] args) {
           StringHTMLText="<p>我的<br/>评论</p>";
           Stringtext=htmlEncode(HTMLText);
           System.out.println(text);
      }
      public static String htmlEncode(String source) {
        if(source == null) {
           return "";
        }
       String html = "";
       StringBuffer buffer = new StringBuffer();
        for(int i = 0; i < source.length(); i++) {
           char c = source.charAt(i);
           switch (c) {
           case '<':
               buffer.append("<");
               break;
           case '>':
               buffer.append(">");
               break;
           case '&':
               buffer.append("&");
               break;
           case '"':
               buffer.append(""");
               break;
           case 10:
           case 13:
               break;
           default:
               buffer.append(c);
           }
        }
       html = buffer.toString();
       return html;
    }
}

输出结果为:&lt;p&gt;我的&lt;br/&gt;评论&lt;/p&gt;



2、HTML标签反转义:

public static void main(String[] args) {
	String HTMLText="<p>我的<br/>评论</p>";
	System.out.println(StringEscapeUtils.unescapeHtml(HTMLText));
}
public static void main(String[] args) {
	String HTMLText="<p>我的<br/>评论</p>";
	System.out.println(StringEscapeUtils.unescapeHtml(HTMLText));
}

输出结果为:<p>我的<br/>评论</p>,

发布了16 篇原创文章 · 获赞 16 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/xiaoxiangshenjian/article/details/75944237