Passing json data from servlet to jsp to js file

I got this servlet that creates JSON data, and I want to transfer this data to a jsp page that should display the data using InfoVis tools.

servlet.java

JSONObject json = new JSONObject(); JSONArray toplevel = new JSONArray(); JSONObject sublevel; try{ json.put("id", "node" + 0); json.put("name", "name" + 0); int count = 5; for(int i=1; i < count; i++){ sublevel = new JSONObject(); sublevel.put("id", "node" + i); sublevel.put("name", "name" + i); toplevel.put(sublevel); } json.put("children", toplevel); } catch (JSONException jse) { } request.setAttribute("jsonString", json.toString()); RequestDispatcher dispatcher = request.getRequestDispatcher("graph.jsp"); dispatcher.forward(request, response); 

The following code is provided by the InfoVis Toolkit, and I'm not sure if it can be changed. Or at least I don't have enough experience in JS to change it.

graph.jsp

 <body onload="init('${jsonString}');"> 

spacetree.js

 function init(jsonString){ var json = jsonString; 

Initial function call only

 <body onload="init()"> 

but the init () function has a JSON hardcoded variable, which, of course, is not useful at all. Therefore, I am looking for a way to make this dynamic. But since theres quotes inside the line now completely messed up the onload = init () function call ..

+4
source share
2 answers

A cheap and easy way is to change the JSP so that it outputs this:

 <script> var theData = ${jsonString}; </script> <body onload="init(theData);"> 

The disadvantage of this is that it creates a global variable, but if you call init this way, init already global, so the ship sailed. :-)

+6
source

You do not need to discard JSON as a string - this is valid JavaScript syntax:

 <body onload='init(${jsonString})'> 

When this is displayed by JSP, the end result - HTML sent to the browser: - will look something like this:

 <body onload='init({"something": "some value", "whatever": "your data looks like"})'> 

Now the only thing you might want to do is HTML JSON encoding, as you drop it as the value of the HTML attribute:

 <body onload='init(${fn:escapeXml(jsonString)})'> 

Then your init function can expect a ready-to-use JavaScript object, without having to call the JSON parser at all.

+2
source

All Articles