44

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
Slartibartfast
  • 8,735
  • 6
  • 41
  • 45
Free Wildebeest
  • 7,272
  • 8
  • 38
  • 42

1 Answers1

60

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)}
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
Slartibartfast
  • 8,735
  • 6
  • 41
  • 45
  • 10
    Be careful as there is a difference between escaping XML and HTML. – Adam Gent Jun 01 '11 at 12:14
  • In most cases escaping XML is sufficient. BTW, the two code examples above work exactly the same. (c:out also escapes Xml, not Html). – rustyx Jan 25 '12 at 13:00
  • 1
    If the concern is XSS prevention in HTML, XML escape should be sufficient (trying not get into xml vs. html advocacy here ...) – Alex Lehmann Jul 19 '12 at 09:47
  • @AdamGent: can you give an example of a difference between escaping XML and HTML? – priomsrb Jan 23 '13 at 01:15
  • 4
    Yeah 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: http://en.wikipedia.org/wiki/Character_encodings_in_HTML – Adam Gent Jan 23 '13 at 01:20
  • 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](http://site.jatl.googlecode.com/hg/apidocs/com/googlecode/jatl/MarkupUtils.html). I have a project called [JATL](http://code.google.com/p/jatl/) that makes generating valid XHTML programmatically easier and respects the difference. – Adam Gent Jan 23 '13 at 01:23
  • There are more differences between escapeXml and escapeHtml mentioned here: http://stackoverflow.com/questions/3735900/what-is-the-difference-between-escapexml-and-escapehtml – priomsrb Jan 23 '13 at 01:24
  • 3
    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! – MasterScrat Apr 27 '16 at 13:51