16

I know there is already questions about that, but I just can´t simply get this work, I have a JSP file with a java variable in it:

String test = "Hello";

And I need to read this value in the Javascript embedded in the same JSP file, I tried so many options, but it is not working, and for security I don't want pass the value using the URL or hidden values.

Any ideas of how get this working?

5 Answers 5

11

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

var myvar = '${jspvar}';
Sign up to request clarification or add additional context in comments.

1 Comment

I needed access to a JSP variable inside a <script> tag and this worked a treat 👌It should be the accepted answer 🙏
7

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

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

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

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

Comments

2

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

<input type="submit" value="view" onclick="callpro('<%= varname %>')" />

Comments

1
var jsvariable="<%=test%>";

4 Comments

I already tried that: var jsvariable="<%=test%>"; But it doesn´t work :(
what does "does not work" mean? what is the output HTML? post the full JSP please.
The variable that I try to pass always is received empty, In other words document.getElementById("Id").value; does not return anything
@user2596007 please, provide the whole JSPage.
1

One thing to note is that you could namespace those variables in this way:

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

The technique is from "Javascript: The Good Parts" Book.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.