Passing a variable from JSP to Javascript

I know that this already exists, but I just canโ€™t get this working, I have a JSP file with a java variable in it:

String test = "Hello";

And I need to read this value in Javascript embedded in the same JSP file, I tried so many parameters, but it doesnโ€™t work, and for security, I donโ€™t want to pass the value using a URL or hidden values.

Any ideas on how this works?

+8
javascript variables parameter-passing jsp web
source share
5 answers

I know this one is old, but it worked for me:

 var javaScriptVar="<%out.print(javaString);%>"; 

you need to make sure that if you are using an external js file (from a jsp file), the above line should be before the "include" script tag. for example, this is a jsp file:

 var javaScriptVar="<%out.print(javaString);%>"; <script src="some_location/test.js"></script> 
+5
source share

The best way to do this is to use something like the following in your javascript code;

 var myvar = '${jspvar}'; 
+4
source share

You can pass the value by calling some methods in the html part ..

 <input type="submit" value="view" onclick="callpro('<%= varname %>')" /> 
+2
source share
 var jsvariable="<%=test%>"; 
+1
source share

It should be noted that you can skip these variables this way:

var MYAPP.javaScriptVar="<%out.print(javaString);%>";

This method is from Javascript: The Good Parts.

+1
source share

All Articles