0

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?

2
  • do you need the value changed on server side reflected on client aswell or just load time value ? Commented Jan 15, 2013 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. Commented Jan 15, 2013 at 22:50

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

I am just using pure servlet
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.

2 Comments

It's a bad idea to promote the usage of scriptlets. Refer to: How to avoid Java Code in JSP-Files?
The example is using JSTL, but I'll delete the Scriptlet reference as suggested

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.