Access Java/Servlet/Jsp/Jstl/El Variables in JavaScript

Access Java / Servlet / JSP / JSTL / EL variables in JavaScript

You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.

Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:

<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>

Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:

<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>

Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.

If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.

If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.

String someObjectAsJson = new Gson().toJson(someObject);

Note that this way you don't need to print it as a quoted string anymore.

<script>var foo = ${someObjectAsJson};</script>

See also:

  • Our JSP wiki page - see the chapter "JavaScript".
  • How to escape JavaScript in JSP?
  • Call Servlet and invoke Java code from JavaScript along with parameters
  • How to use Servlets and Ajax?

Reading a jstl variable in javascript code.

Just write the Expression Language directly in your JavaScript code:

$("#textBoxInp").keyup(function() {
var userId = '${userId}';
});

Note that this won't work if the JavaScript code is placed in a external file and is invoked in the JSP. In this case, you may refer to one of the four ways that BalusC explain here: Mixing JSF EL in a Javascript file (he explains five, but one of them is JSF specific).

How to access variables from the ModelAndView in JavaScript code

Yes of course you can have something like this. Declare var in jsp

<c:set var="yourJspVar" scope="session" value=" your object"/>

and in java-script set variable like

<script>
var jsVar = '${yourJspVar}';
alert(jsVar);
</script>

JSP : using java variable in Javascript

Just assign the value to your Javascript variable.

<script type="text/javascript">
var count = '<%= totalCount %>';
</script>

But using scriptlets been highly discouraged and shift to JSTL as soon as possible.

Read : How to avoid Java code in JSP files?

As others pointed out, do not create unnecessary hidden elements on DOM. If you really want to use this variable across files declare this variable on top. Even before script includes, so that it avail across all the files.

Example:

 <script type="text/javascript">
var count = '<%= totalCount %>';
</script>
<script type='text/javascript' src='js/blah.js'></script>
<script type='text/javascript' src='js/blahblah.js'></script>

How to let JavaScript use the variable from server side?

Write out your bean value to an HTML element's value or an attribute of the HTML element. Give the HTML element an ID. Use Javascript to retrieve the element by ID, or by another accessor, and you can access the value. Are you using struts or another Servlet framework?

A simple example

JSP:

 <div id="employeeName">
<jsp:getProperty name="employee" property="firstName"/>
</div>

HTML:

<script type="text/javascript">var el = document.getElementById("employeeName");</script>

Javascript/JSP: How to pass JSP variables value on one page to javascript variables on next page?

Just let JSP print it as if it is a JS variable. Assuming that you've variable ${foo} in JSP:

<script>var foo = '${foo}';</script>

This will end up in webbrowser as

<script>var foo = 'somevalue';</script>

Keep in mind: JSP runs at webserver and produces HTML. JS is part of HTML and runs at webbrowser.

See also:

  • How to communicate between JavaScript and Java/JSP/JSF?


Related Topics



Leave a reply



Submit