2

I have hard-coded data into a .jsp file. What I want to do is populate a JavaScript array with data sent from the server.

I have tried to send the data from another .jsp page, but I cannot figure out how to convert it into a JavaScript var for me to be able to use it in my page, I also have started using JSON objects, but before I continue I just need some guidance on what the best way to do this would be.

That is: populate a JavaScipt array on a .html or .jsp file from the server. The array will then be used for Google Maps API.

Let me know if you have any questions:

thanks

2 Answers 2

3

If it's hardcoded, why not making it a JS variable directly?

var foo = [{
    "name1": "value1a",
    "name2": "value2a"
},{
    "name1": "value1b",
    "name2": "value2b"
}];

Or if it's hardcoded in Java side and you intend to use it in JS side as well, then convert the Java object to JSON using one of the many JSON serializers/parsers available. At the bottom of json.org you can find an overview of all available JSON APIs in Java. One of them is Google Gson. It's able to convert for example a List<SomeBean> to a JSON string as follows

String jsonString = new Gson().toJson(someBeans);

You can then just let JSP print it as if it's a JS variable, assuming that it's stored as a request attribute:

var foo = ${jsonString};
Sign up to request clarification or add additional context in comments.

2 Comments

+1, cleaner answer. Lazy to search, but will that escape representation of objects whose stringified version contains </script> ?
@Thrustmaster: Yes, Gson will by default JS-escape the bean properties. This is also configureable.
1

This is pretty simple:

  1. You must make sure your JSP produces correct JavaScript as output.
  2. Include the JSP with a <script> tag (i.e. the JSP needs to be accessible with a URL; put that URL into the src attribute).

Example for the JSP code:

var data = [<% ...generate array elements here... %>];

That will allow you to access the variable data in all JavaScript that is executed afterwards. In your case, you will include the script as the first thing in the page so every other script can use it.

Neat trick: Add a query parameter to specify the variable name:

var <%=request.getParameter("name") %> = [<% ...generate array elements here... %>];

and include it with

<script src="...url...?name=data" type="text/javascript">

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.