Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output JSTL escaped? [duplicate]

I am retrieving a value from our DB using JSTL. I am inserting it right into some javascript to use it as a variable. I need the output of the value the JSTL is holding to be escaped because if there are single or double quotes it breaks my script. The value is user specified.

Example:

Doing the following:

<c:set var="myVar" value="Dale's Truck"/>

<script type="text/javascript">
    var mayVar = '${myVar}';
</script>

Would actually end up looking like:

<script type="text/javascript">
    var mayVar = 'Dale's Truck';//extra single quote breaks the JS
</script>

So I need to convert the JSTL var to be escaped like "Dale%27s Truck" before is gets to the JS because its already too late when it gets to my JS to be able to do it in JS.

like image 959
UpHelix Avatar asked Jul 15 '10 21:07

UpHelix


2 Answers

Try using fn:replace:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<c:set var="myVar" value="Dale's Truck" />
<c:set var="search" value="'" />
<c:set var="replace" value="%27" />

<c:set var="myVar" value="${fn:replace(myVar, search, replace)}"/>

or you can escape the single quote with a backslash:

<c:set var="replace" value="\\'" />

or if you don't even want to do all that and you are sure that the string won't contain double quotes, why not do:

var myVar = "${myVar}"; //string enclosed with double quotes instead of single quotes

But if the string has double quotes, you will still need to escape them:

<c:set var="search" value="\"" />
<c:set var="replace" value="\\\"" />
like image 108
Vivin Paliath Avatar answered Nov 15 '22 17:11

Vivin Paliath


The other answer was already accepted, but David Balazic made a great point. The <spring:escapeBody> function works best.

<spring:escapeBody htmlEscape="false" javaScriptEscape="true">${myVar}</spring:escapeBody>

like image 42
Anthony Chuinard Avatar answered Nov 15 '22 19:11

Anthony Chuinard