2

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hey this worked! Thanks. I thought I tried this, but I think I used Integer instead of String for my info 2D array. This was only giving me the first item in the sub-list.
Glad to know this helped.
I have a similar question. The only difference is that my 2d array index are of String type. Like this: info : [["property","one"],["class","name"]] How can I retrieve this info array contents in servlet using request object then?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.