We have jsp, which uses some java beans to create some variables to be used inside jsp. I am wondering how to share those variables with javascript?
Asked
Active
Viewed 2,376 times
0
-
do you need the value changed on server side reflected on client aswell or just load time value ? – jmj Jan 15 '13 at 22:42
-
Variable is an ambiguous term in this context. You need to serialize the data to a form that can be rendered as a string and interpreted by a script in the browser. How you do that depends on the complexity of the data. It would also help if you stated the technologies and versions in play. – McDowell Jan 15 '13 at 22:50
2 Answers
1
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>

KyleM
- 4,445
- 9
- 46
- 78
1
You can use JSTL tags to output your Bean Values in JavaScript code. It's far from been elegant, but it works. For example, this is a fragment of a JSP page:
<script type="text/javascript">
<c:if test="${imServerSideBean eq false}" >
var imAJSVariable= new Object();
</c:if>
//More code here
</script>
<html>
//Code continues
You're using JSTL to select make visible a JavaScript variable or not.

Carlos Gavidia-Calderon
- 7,145
- 9
- 34
- 59
-
It's a bad idea to promote the usage of scriptlets. Refer to: [How to avoid Java Code in JSP-Files?](http://stackoverflow.com/q/3177733/1065197) – Luiggi Mendoza Jan 15 '13 at 22:47
-
The example is using JSTL, but I'll delete the Scriptlet reference as suggested – Carlos Gavidia-Calderon Jan 15 '13 at 22:49