I have to send to a servlet two arrays, i use an Ajax POST call that sends a JSON object, and then I have to read the data sent in two lists or arrays in a servlet class in java. I prefer not to use jQuery for Ajax call. I am not very familiar with json, i used some code found in stackoverflow and i can't understand if there is a problem in sending or parsing data.
Here is the method to make the Ajax call in Javascript, where cback is the callback function, method = "POST" and url is the url of the servlet:
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);
}
Here is the doPost method in the servlet controller specified by the url. Here is where i found the problem: after doing getParameter, strings json1 and json2 are 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());
//...
}