Reading a JSP variable from JavaScript

JavaJavascriptJsp

Java Problem Overview


How can I read/access a JSP variable from JavaScript?

Java Solutions


Solution 1 - Java

alert("${variable}");

or

alert("<%=var%>");

or full example

<html> 
<head>
<script language="javascript"> 

function access(){ 
  <% String str="Hello World"; %>
   var s="<%=str%>"; 
   alert(s); 
} 

</script> 
</head> 

<body onload="access()"> 
</body> 

</html>

Note: sanitize the input before rendering it, it may open whole lot of XSS possibilities

Solution 2 - Java

The cleanest way, as far as I know:

  1. add your JSP variable to an HTML element's data-* attribute
  2. then read this value via Javascript when required

My opinion regarding the current solutions on this SO page: reading "directly" JSP values using java scriplet inside actual javascript code is probably the most disgusting thing you could do. Makes me wanna puke. haha. Seriously, try to not do it.

The HTML part without JSP:

<body data-customvalueone="1st Interpreted Jsp Value" data-customvaluetwo="another Interpreted Jsp Value">
    Here is your regular page main content
</body>

The HTML part when using JSP:

<body data-customvalueone="${beanName.attrName}" data-customvaluetwo="${beanName.scndAttrName}">
    Here is your regular page main content
</body>

The javascript part (using jQuery for simplicity):

<script type="text/JavaScript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript">
    jQuery(function(){
        var valuePassedFromJSP = $("body").attr("data-customvalueone");
        var anotherValuePassedFromJSP = $("body").attr("data-customvaluetwo");

        alert(valuePassedFromJSP + " and " + anotherValuePassedFromJSP + " are the values passed from your JSP page");
});
</script>

And here is the jsFiddle to see this in action http://jsfiddle.net/6wEYw/2/

Resources:

Solution 3 - Java

Assuming you are talking about JavaScript in an HTML document.

You can't do this directly since, as far as the JSP is concerned, it is outputting text, and as far as the page is concerned, it is just getting an HTML document.

You have to generate JavaScript code to instantiate the variable, taking care to escape any characters with special meaning in JS. If you just dump the data (as proposed by some other answers) you will find it falling over when the data contains new lines, quote characters and so on.

The simplest way to do this is to use a JSON library (there are a bunch listed at the bottom of http://json.org/ ) and then have the JSP output:

<script type="text/javascript">
    var myObject = <%= the string output by the JSON library %>;
</script>

This will give you an object that you can access like:

myObject.someProperty

in the JS.

Solution 4 - Java

   <% String s="Hi"; %>
   var v ="<%=s%>"; 

Solution 5 - Java

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 

    <title>JSP Page</title>
    <script>
       $(document).ready(function(){
          <% String name = "phuongmychi.github.io" ;%> // jsp vari
         var name = "<%=name %>" // call var to js
         $("#id").html(name); //output to html
           
       });
    </script>
</head>
<body>
    <h1 id='id'>!</h1>
</body>

Solution 6 - Java

I know this is an older post, but I have a cleaner solution that I think will solve the XSS issues and keep it simple:

<script>
   let myJSVariable = <%= "`" + myJavaVariable.replace("`", "\\`") + "`" %>;
</script>

This makes use of the JS template string's escape functionality and prevents the string from being executed by escaping any backticks contained within the value in Java.

You could easily abstract this out to a utility method for re-use:

public static String escapeStringToJS(String value) {
   if (value == null) return "``";
   return "`" + value.replace("`", "\\`") + "`";
} 

and then in the JSP JS block:

<script>
   let myJSVariable = <%= Util.escapeStringToJS(myJavaVariable) %>;
</script>

The result:

<script>
   let myJSVariable = `~\`!@#$%^&*()-_=+'"|]{[?/>.,<:;`;
</script>

Note: This doesn't take separation of concerns into consideration, but if you're just looking for a simple and quick solution, this may work.

Also, if you can think of any risks to this approach, please let me know.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSiddiquiView Question on Stackoverflow
Solution 1 - JavajmjView Answer on Stackoverflow
Solution 2 - JavaAdrien BeView Answer on Stackoverflow
Solution 3 - JavaQuentinView Answer on Stackoverflow
Solution 4 - Javauser467871View Answer on Stackoverflow
Solution 5 - JavaphuongmychiView Answer on Stackoverflow
Solution 6 - JavaColinView Answer on Stackoverflow