Reputation: 9905
I have a query on retrieving data sent as JSON from a JavaScript, inside a Java servlet. Following is what I am doing...
This is the part of the code inside JavaScript making 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);
}
}
On making this request I try to retrieve the parameters sent from JavaScript in a Servlet, but while doing so I was firstly confused on how to retrieve the dat from the request
I used the following in my servlet:
NOTE : the content Type in my Servlet is set to : apllication/json
response.setContentType("application/json");
request.getParameterMap();
the above showed me the data as below, but I was not able 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 Exception of null which was expected.
request.getParametervalues("items");
Among the others i tried where request.getParameter(); request.getParameterNames(); but in vain...
Am I in a wrong direction? Please guide me! Please let me know how to retieve these value.
Thank You for reading this long post...
Sangeet
Upvotes: 4
Views: 8146
Reputation: 1108712
The request parameter map is a Map<String, String[]>
where the map key is the parameter name and map value are the parameter values --HTTP allows more than one value on the same name.
Given the printout of your map, 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 a bit more dynamics, 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 response content type is irrelevant when it comes to gathering the request parameters.
Upvotes: 3