How can I escape special HTML characters in JSP?

82,713

Short answer:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:out value="${myString}"/>

there is another option:

<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
${fn:escapeXml(myString)}
Share:
82,713
daxsorbito
Author by

daxsorbito

Symbian/C++/Java/Python/Perl developer, architect and general firefigher in the UK.

Updated on July 09, 2022

Comments

  • daxsorbito
    daxsorbito almost 2 years

    Before I go and create a custom tag or Java method to do it, what is the standard way to escape HTML characters in JSP?

    I have a String object and I want to display it in the HTML so that it appears to the user as is.

    For example:

    String a = "Hello < World";
    

    Would become:

    Hello &lt; World
    
  • Adam Gent
    Adam Gent about 13 years
    Be careful as there is a difference between escaping XML and HTML.
  • rustyx
    rustyx over 12 years
    In most cases escaping XML is sufficient. BTW, the two code examples above work exactly the same. (c:out also escapes Xml, not Html).
  • Alex Lehmann
    Alex Lehmann almost 12 years
    If the concern is XSS prevention in HTML, XML escape should be sufficient (trying not get into xml vs. html advocacy here ...)
  • priomsrb
    priomsrb over 11 years
    @AdamGent: can you give an example of a difference between escaping XML and HTML?
  • Adam Gent
    Adam Gent over 11 years
    Yeah the famous dreaded &apos;: The character entity references &lt;, &gt;, &quot; and &amp; are predefined in HTML and SGML, because <, >, " and & are already used to delimit markup. This notably does not include XML's &apos; (') entity. For a list of all named HTML character entity references, see List of XML and HTML character entity references (approximately 250 entries). -- From Wikipedia: en.wikipedia.org/wiki/Character_encodings_in_HTML
  • Adam Gent
    Adam Gent over 11 years
    What also regularly pisses me off is there is a difference between attribute content escaping and element content escaping. That is the content you put in attributes needs be escaped differently. I have a project called JATL that makes generating valid XHTML programmatically easier and respects the difference.
  • priomsrb
    priomsrb over 11 years
    There are more differences between escapeXml and escapeHtml mentioned here: stackoverflow.com/questions/3735900/…
  • MasterScrat
    MasterScrat about 8 years
    Note that this will not prevent all XSS vulnerabilities! if you have var show = ${fn:escapeXml(show)} you don't need either < or " to exploit it!