When sending data to a servlet, I utilize an Ajax POST call to send a JSON object containing two arrays. In the servlet class in Java, I need to read this data sent in two lists or arrays. I am avoiding the use of jQuery for the Ajax call and am not very familiar with JSON. Although I found some code on Stack Overflow to help with this task, I am unsure if there is an issue with sending or parsing the data.
Below is the JavaScript method for making the Ajax call, with "cback" representing the callback function, "method" as "POST," and "url" as the servlet URL:
function makeCall(method, url, from, to, cback) {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
cback(req)
};
req.open(method, url);
var obj = {};
obj["from"] = from;
obj["to"] = to;
var data = JSON.stringify(obj);
req.send(data);
}
Continuing, here is the doPost method within the servlet controller specified by the URL. The issue arises when attempting to retrieve the data using getParameter, as the strings "json1" and "json2" end up being null:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//...
String json1 = request.getParameter("from");
String json2 = request.getParameter("to");
Gson gson = new Gson();
ArrayList<Double> listFrom = gson.fromJson(json1,
new TypeToken<ArrayList<Categoria>>() {}.getType());
ArrayList<Double> listTo = gson.fromJson(json2,
new TypeToken<ArrayList<Double>>() {}.getType());
//...
}