1

In a project using JSP and Spring, what would be the simplest way to escape an EL expression value for JavaScript first, then for HTML?

Imagine this use:

<a onclick='alert("${note}");'>Foo</a>

This is susceptible to XSS or plain syntax errors, as the variable value can contain quote, less-than and other characters.

What I came up is:

<a onclick='alert("<c:out value="${null}"
><s:escapeBody htmlEscape="false" javaScriptEscape="true"
>${variable}</s:escapeBody></c:out>");'>Foo</a>
<!-- this escapes first the inner tags body for JS,
     then c:out uses that (because its value attribute
     is null, it uses what is in its own body) and
     escapes it for HTML/XML -->

It is rather clumsy, so I'm looking for a more elegant way.

(note that using just <s:escapeBody htmlEscape="true" javaScriptEscape="true"> is incorrect as the tag escapes first for HTML and then for JS, so for example it would fail on the value of a"b)

David Balažic
  • 1,319
  • 1
  • 23
  • 50
  • @BalusC the supposed duplicate asks about escaping JS, here the question is about HTML and JS. The answer there could be used as _part_ of an answer here. – David Balažic Oct 06 '16 at 14:05

1 Answers1

0

To avoid getting clumsy code, I would suggest you create a small custom taglib which provides a function exactly for that. You can implement that very easily by using StringEscapeUtils in commons-lang.

Then you can write:

<a onclick='alert("${foo:escapeJsHtml(note)}");'>Foo</a>
Rüdiger Schulz
  • 2,588
  • 3
  • 27
  • 43