Q:

Safe way to send value from jsp to javascript

I have to secure a java web application against XSS attacks. There are parts of the code that look like this:
<script>
  jsvariable = ${jspvariable}
  use(jsvariable)
<script>

My first tough was to do something like this:
<script>
  jsvariable = ${fn:escapeXml(jspvariable)}
  use(jsvariable)
<script>

But escapeXml doesn't avoid XSS inside a script tag. What's the correct way to send a value from jsp to javascript.

A:

You could write your jsp data in a text/json block which will be ignored by the browser:
<script id="demo" type="text/json">
  ${jspvariable}
</script>

You can then parse the values in your javascript file on dom ready:
console.log(JSON.parse(document.getElementById('demo').innerHTML));

A XSS injection could lead only to a JSON parse error

