What is the difference between escapeXml and escapeHtml?

后端 未结 4 1866
情话喂你
情话喂你 2020-12-16 13:32

I would like to escape characters in JSP pages. Which is more suitable, escapeXml or escapeHtml?

相关标签:
4条回答
  • 2020-12-16 14:03

    There's no such thing as escapeHtml in JSP. You normally use <c:out escapeXml="true"> (it by the way already defaults to true, so you can omit it) or fn:escapeXml() to escape HTML in JSP.

    E.g.

    <c:out value="Welcome, ${user.name}" />
    <input name="foo" value="${fn:escapeXml(param.foo)}" />
    

    It will escape them as XML entities which works perfectly fine in plain HTML as well. They are only literally called XML entities because HTML entities are invalid in XML.

    See also:

    • Java 5 HTML escaping To Prevent XSS
    • Escaping html in Java
    0 讨论(0)
  • 2020-12-16 14:05

    They're designed for different purposes, HTML has lots of entities that XML doesn't. XML only has 5 escapes:

    &lt; represents "<"
    &gt; represents ">"
    &amp; represents "&"
    &apos; represents '
    &quot; represents "
    

    While HTML has loads - think of &nbsp; &copy; etc. These HTML codes aren't valid in XML unless you include a definition in the header. The numeric codes (like &#169; for the copyright symbol) are valid in both.

    0 讨论(0)
  • 2020-12-16 14:16

    Since you are sending HTML back to the consumer I would go with escapeHtml.

    escapeXml only supports escaping the five basic XML entities (gt, lt, quot, amp, apos) whereas escapeHtml supports escaping all known HTML 4.0 entities.

    0 讨论(0)
  • 2020-12-16 14:20

    Assuming you're referring to commons StringEscapeUtils, escapeXml only deals with <>"'& while escapeHtml covers a richer set of characters.

    0 讨论(0)
提交回复
热议问题