Skip to content Skip to sidebar Skip to footer

Pass A Javascript Object To A Jsp Page Using Jquery

i have in javascript var data = new Object(); and some attributes for this object are: data.name = 'mike'; data.id = 1; i use jquery to pass the object to a jsp page var request =

Solution 1:

  1. Because you are posting to the JSP, make sure that you handle inside a doPost(request, response) method.
  2. Generally, all data passed should be in JSON format. In your case, it should read

    data: {'obj' : data}
    
  3. To parse on the server side, use the org.json library:

    JSONObject obj = (JSONObject) JSONValue.parse(request.getParameter("obj"));
        Iterator<?> keys = obj.keys();            
        //iterate over the properties of the JSON objectwhile( keys.hasNext() ){
            String key = (String)keys.next();
            if( obj.get(key) instanceofJSONObject ){
                //a JSONObject inside the JSONObject
            } else {
                //process
            }
        }
    

    See the docs: JSONObject

Solution 2:

The object of javascript is different from the object of java. The two are not at all comparable. Here you are sending javascript object as is. This should be changed to json string.

data:  'obj='+ JSON.stringify(data),

And also on server you should get the json string and then convert that json to java object by using some of the mechanisms like ObjectMapper

ObjectobjParam= request.getParameter("obj");

ObjectMapperom=newObjectMapper();
om.readValue(objParam.toString(), ...);

Solution 3:

you can pass json data(javascript object converted into json data using json.stringify()) in client side.In service side ,using Gson Libarary you can map json data with java object.

publicclassUser{
privateString userName;
//getters//setters
    }

Json format

{"userName":"test_username"}

Now you can map json data to java object using GSON library.

for example plz refer the below link

https://sites.google.com/site/gson/gson-user-guide

Post a Comment for "Pass A Javascript Object To A Jsp Page Using Jquery"