Get data sent as JSON from JavaScript inside the servlet

I have a request to receive data sent as JSON from JavaScript inside a Java servlet. The following is what I do ...

This is part of the code inside JavaScript that makes a request to a servlet

type : "POST", url: 'getInitialData', datatype: 'json', data : ({items :[{ name: "John", time: "2pm" },{name: "Sam", time: "1pm" }]}), success: function(data) { try{ ////Code to be handeled where response is recieved }catch(e){ alert(e); } } 

While executing this request, I try to get parameters sent from JavaScript to Servlet, but at the same time I was confused at first with how to get data from the request

In my servlet, I used the following:

NOTE. . The content type in my servlets is set to: apllication / json

  response.setContentType("application/json"); request.getParameterMap(); 

the above showed me the data as below, but I could not figure out how to work and get the actual data.

 {items[1][name]=[Ljava.lang.String;@1930089, items[0][time]=[Ljava.lang.String;@860ba, items[1][time]=[Ljava.lang.String;@664ca, items[0][name]=[Ljava.lang.String;@1c334de} 

while the following code gave me a null value exception that was expected.

 request.getParametervalues("items"); 

Among others, I tried where request.getParameter (); request.getParameterNames (); but in vain ...

Am I in the wrong direction? Please guide me! Please let me know how to return this value.

Thanks for reading this long post ...

Sangit

+4
source share
1 answer

The query parameter map is Map<String, String[]> , where the map key is the parameter name and the map value is the parameter value. --HTTP allows you to use more than one value with the same name.

Given the printout of your card, the following should work:

 String item0Name = request.getParameter("items[0][name]"); String item0Time = request.getParameter("items[0][time]"); String item1Name = request.getParameter("items[1][name]"); String item1Time = request.getParameter("items[1][time]"); 

If you want to increase the dynamics a bit, use the following:

 for (int i = 0; i < Integer.MAX_VALUE; i++) { String itemName = request.getParameter("items[" + i + "][name]"); String itemTime = request.getParameter("items[" + i + "][time]"); if (itemName == null) { break; } // Collect name and time in some bean and add to list yourself. } 

Note that setting the content type to the response does not matter when it comes to collecting query parameters.

+3
source

Source: https://habr.com/ru/post/1338479/


All Articles