Java中转义HTML的推荐方法

问题:

在纯Java代码中输出HTML时,是否有推荐的方式来逃避<>"&个字符? (除了手动执行以下操作,就是)。

String source = "The less than sign (<) and ampersand (&amp;) must be escaped before using them in HTML";
String escaped = source.replace("<", "&amp;lt;").replace("&amp;", "&amp;amp;"); // ...
&#91;/code&#93;

<h4>回答:</h4>
 来自<a href="http://commons.apache.org/lang/" rel="noreferrer">Apache Commons Lang</a>的<a href="http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html" rel="noreferrer">StringEscapeUtils</a>

import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
// ...
String source = "The less than sign (<) and ampersand (&amp;) must be escaped before using them in HTML";
String escaped = escapeHtml(source);
&#91;/code&#93;
对于<a href="https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringEscapeUtils.html#escapeHtml4(java.lang.String)" rel="noreferrer">version 3</a>

import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;
// ...
String escaped = escapeHtml4(source);

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: Recommended method for escaping HTML in Java

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

− 5 = 1