user2012998
user2012998

Reputation: 21

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 = $.ajax
({
 url: "test.jsp",
 type: "post",
 data:  'obj='+ data,
success:    function(msg) {
     $('#response').html(msg);},
  error:function (xhr, ajaxOptions, thrownError){
 alert(xhr.status);
 alert(thrownError);
}  
});

in the jsp i say

Object objParam = request.getParameter("obj"); out.println(objParam.name);

this doesn't seem to work. please help.

Upvotes: 2

Views: 4442

Answers (3)

santhoshkumar
santhoshkumar

Reputation: 62

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.

    public class User{
private String 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

Upvotes: 0

zz3599
zz3599

Reputation: 647

  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 object
        while( keys.hasNext() ){
            String key = (String)keys.next();
            if( obj.get(key) instanceof JSONObject ){
                //a JSONObject inside the JSONObject
            } else {
                //process
            }
        }
    

    See the docs: JSONObject

Upvotes: 2

Abhijeet Pawar
Abhijeet Pawar

Reputation: 682

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

Object objParam = request.getParameter("obj");

ObjectMapper om = new ObjectMapper();
om.readValue(objParam.toString(), ...);

Upvotes: 0

Related Questions