0

Im trying to pass an array from javascript to java servlet using Jackson, how this can be done..thanks

2 Answers 2

3

The basic idea should be straightforward:

Server:

doPost(HttpServletRequest req, HttpServletResponse resp)
{
  ObjectMapper mapper = new ObjectMapper();
  ArrayNode rootNode = mapper.readValue(req.getReader(), ArrayNode.class);
}

Client:

Using jQuery (you can also do it with other frameworks, or manually). Load a copy of json2.js to make sure you have JSON.stringify.

jQuery.ajax({
  type: 'POST',
  url: servletURL,
  data: JSON.stringify(jsArray),
  dataType: 'json',
  contentType: 'application/json'
});
Sign up to request clarification or add additional context in comments.

5 Comments

thanks matthew for reply...im using YUI 3, the array reach servlet and everything is ok, but i need to get the right parameter from request. i replaced req.getReader() with req.getParameter("myArray") but still not working
nevermind...its worked i used req.getParameterValues("myArray"), thanks for helping
@Mohammed, if you're using getParameterValues, you're probably not using JSON. You most likely have a regular GET query-string.
i thought its worked...im using Jackson. so is there away to pick specific parameter from HttpServletRequest using ArrayNode rootNode = mapper.readValue(req.getReader(), ArrayNode.class); ??
Okay, it looks like you do need both getParameterValues and Jackson because of the way YUI is sending the request.
0

For passing the array from the browser to the server side you don't need Jackson. You just need Ajax. For example, using jQuery you can do it this way:

$.ajax({
  url: 'your servlet url',
  data: yourArray
});

Then on the server side, you might want to deserialize the JSON into a JavaBean or, in your case, a java.util.List using Jackson. You can do that this way:

ObjectMapper mapper = new ObjectMapper();
List array = mapper.readValue(jsonText, List.class);

Where jsonText contains the String representation of yourArray that is sent to the server-side from the browser.

1 Comment

Your client code sends the data in query-string format, not JSON.

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.