user439299 user439299 - 6 months ago 27
Javascript Question

How do I read a 2D array from jQuery in a Java Servlet?

I want to send arbitrarily complex array data to a Java servlet, but have no idea how to read it on the servlet side. Here is the client side:

var data = {
name : 'Jack',
age : 30,
info : [ [1,2] , [3,4] , [5,6] ],
info2: [1,2,3]
}

$.ajax({
url: someURL,
data: data,
success: function(resp) { console.log(resp); }
});


I know I can use JSON.stringify and then parse it out on the server side, but for the sake of this question, I can't change the front end code. How do I read the "info" variable on the server side using the HttpServletRequest object? I also know you can do something like this for single arrays:

String[] info2 = request.getParameterValues("info2[]");


But this doesn't work with 2D arrays or more complicated arrays.

Any ideas?

Answer

If info is known to be a fixed-length array

private static final int INFO_LEN = 3;

You can collect its values inside your servlet as

String[][] info = new String[INFO_LEN][];

for (int i = 0; i < info.length; i++) {
    info[i] = request.getParameterValues("info["+i+"][]");
}

If the length is not known beforehand, collect the values in a loop until you get a null.