lorisgoglia
lorisgoglia

Reputation: 53

Ajax send JSON object with two arrays to a servlet and parsing in java servlet without jQuery

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());
                
      //...
}

Upvotes: 2

Views: 308

Answers (1)

Musa
Musa

Reputation: 97672

Your ajax is sending JSON but your servelet is expecting form data, that has JSON in it.
To send the data like your server expects encode each array to JSON and send them as form data

function makeCall(method, url, from, to, cback) {
    var req = new XMLHttpRequest(); 
    req.onreadystatechange = function() {
        cback(req)
    }; 
    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    req.open(method, url);
  
    var params = new URLSearchParams({to: JSON.stringify(to), from: JSON.stringify(from)});
    req.send(params.toString());            
}

Upvotes: 3

Related Questions