views:

2185

answers:

4

i have a json object in a javascript file. i have to pass this object to a jsp file.the jsp picks up this object and processes it. how can i do it?

A: 

The same way you get any other data from a web browser to an HTTP server.

Encode it in an HTTP request by submitting a form / setting the window location / using XMLHttpRequest / etc.

David Dorward
A: 

Use StringTree JSON parser library to parse the JSON into java objects. Pass the JSON object to your servelet using either a POST or a GET or AJAX

mkoryak
+1  A: 

There are a couple of issues you need to resolve first, are you doing this in an AJAX style of request? is this a form submission? is there going to be on-going interaction within the page-session between the client/server passing JSON objects back-and-forth?

Lets tackle the simple case of a form submission, once you get that you should be able to get the remaining cases going as they are just "extensions" of this base case. Say you have some form that will submit the data in some field:

<form name='my_form' id='my_ford_id'>
  <input type='hidden' name='my_input_field' />
</form>

then at some point in time you have a piece of code that executes and you have your JSON object

function myFunction() {
  var json_data = getJsonData();
  document.forms['my_form']['my_input_field'].value = json_data;
  document.forms['my_form'].submit();
}

You will then on the JSP side receive this data as a JSON string inside of a form field, at which point you need to process it, lets assume you have some kind of a JSON library available to you, the code might look something like this:

<%
  String myInputField = request.getParameter("my_input_field");
  if(myInputField != null) {
    try {
      JSONObject myObject = new JSONObject(myInputField);
    }
    catch(JSONException e) {

    }
  }
%>

If you need an "AJAX" style of interaction, you will be making a number of such requests in the page, but fundamentally it falls back to the original problem of submitting the data. Since you are using forms in this example, and JSP, you don't have to worry at any point about encoding, the browser/server will take care of things for you.

Michael
where can we get JSONObject..is it a 3rd party API
cdb
http://json-lib.sourceforge.net/
cjstehno
A: 

"JSON" Site helps u to manage Json Objects in JSp/java. U have 2 convert the string obtained from javascript to a json object.Then manage it easily.

cdb