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)}
Author by
daxsorbito
Symbian/C++/Java/Python/Perl developer, architect and general firefigher in the UK.
Updated on July 09, 2022Comments
-
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 < World
-
Adam Gent about 13 yearsBe careful as there is a difference between escaping XML and HTML.
-
rustyx over 12 yearsIn 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 almost 12 yearsIf the concern is XSS prevention in HTML, XML escape should be sufficient (trying not get into xml vs. html advocacy here ...)
-
priomsrb over 11 years@AdamGent: can you give an example of a difference between escaping XML and HTML?
-
Adam Gent over 11 yearsYeah the famous dreaded
'
: The character entity references <, >, " and & are predefined in HTML and SGML, because <, >, " and & are already used to delimit markup. This notably does not include XML's ' (') 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 over 11 yearsWhat 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 over 11 yearsThere are more differences between escapeXml and escapeHtml mentioned here: stackoverflow.com/questions/3735900/…
-
MasterScrat about 8 yearsNote 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!