As a note, one of the things you have to worry about when using JSP to generate Javascript is that, out of the box, there's no facility provided to "sanitize" text for that context. Specifically, in this example, if you want to put ${entry.value}
into a Javascript string:
var someValue = '${entry.value}';
then you have to make sure that the value will be correctly parsed as a Javascript string. What definitely will NOT work is:
var someValue = '${fn:escapeXml(entry.value)}';
Why not? Because fn:escapeXml()
is about sanitizing strings so that an XML or HTML parser won't see any metacharacters in the strings. XML and HTML have their own sensitivities, and they're just completely different from Javascript's syntax. An ampersand inside a Javascript string constant is just an ampersand, for example. However, in our example here, if ${entry.value}
is the name of your Irish uncle, then upon expansion we'd have:
var someValue = 'John O'Hara';
and that's a Javascript syntax error.
To my knowledge, the JSTL/EL doesn't yet have a standardized JSON transformer. Grabbing one of the many JSON toolkits available (all with their own pluses and minuses) and wiring it up to an EL function of your own is one approach to solving this issue. Another, simpler approach is to just write your own variation of fn:escapeXml()
for the purpose of "escaping" Javascript strings. It should worry about quote characters, the family of special control characters like newline and backspace, the backslash character, and Unicode characters outside the 7-bit range. With something like that, you can safely write:
var someValue = '${yourTld:escapeJS(entry.value)}';
and be confident that the generated text will be something like:
var someValue = 'John O\'Hara';