Issue
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.
Solution
The file extension .json
is not so relevant. It's just all about the HTTP Content Type header. As long as it's application/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 certain url-pattern
, processes the request parameters or pathinfo accordingly and writes a JSON string to the response in the doGet()
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:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String country = request.getParameter("country");
Map<String, String> cities = cityDAO.find(country);
String json = new Gson().toJson(cities);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
Map such a servlet on an url-pattern
of /cities
in web.xml
(or if you want a bit more SEO friendly approach, map it on /cities/*
and use request.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).
$(document).ready(function() {
$('#country').change(function() {
var selectedCountry = $(this).val();
var servletUrl = 'cities?country=' + selectedCountry;
$.getJSON(servletUrl, function(options) {
var city = $('#city');
$('>option', city).remove(); // Clean old options first.
if (options) {
$.each(options, function(value, label) {
dropdown2.append($('<option/>').val(value).text(label));
});
} else {
dropdown2.append($('<option/>').text("Please select country"));
}
});
});
});
Here is the appropriate HTML example of the JSP:
<select id="country" name="country">
<c:forEach items="${countries}" var="country">
<option value="${country.key}">${country.value}</option>
</c:forEach>
</select>
<select id="city" name="city">
<option>Please select country</option>
</select>
(assuming that ${countries}
is an Map<String, String>
in application scope)
Hope this clears the one and other :)
See also:
Answered By - BalusC