A while back I was given the answer of using JSON to pass things from my application to JavaScript. What I don’t understand is how I actually pass the object to JavaScript I see that you have to use a .json file.
And then what? I am able to convert my Java objects to JSON objects but it’s passing that I can’t get my head around. I am using JSP and Servlets to write my application.
The file extension
.jsonis not so relevant. It’s just all about the HTTP Content Type header. As long as it’sapplication/json, the webbrowser knows perfectly what to do with it. In terms of JSP/Servlet you basically need to create a servlet class which listens on a certainurl-pattern, processes the request parameters or pathinfo accordingly and writes a JSON string to the response in thedoGet()method.Here’s a fictive example of a servlet which returns city option value/label pairs based on the selected value of a country dropdown, it uses Google Gson to convert fullworthy Java objects to JSON in an oneliner:
Map such a servlet on an
url-patternof/citiesinweb.xml(or if you want a bit more SEO friendly approach, map it on/cities/*and userequest.getPathInfo()instead).Finally, in the JS code which is executed during onchange of a country dropdown, you just let it fire an asynchronous (ajaxical) request on this servlet with the selected country as parameter (or pathinfo). I’ll give a jQuery based example since it insanely eases firing ajax requests and traversing/manipulating HTML DOM (the "raw" JS code would otherwise have been up to 5 times as long).
Here is the appropriate HTML example of the JSP:
(assuming that
${countries}is anMap<String, String>in application scope)Hope this clears the one and other 🙂
See also:
[json]+[jsp].[json]+[servlets].