Reputation: 21
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
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
Reputation: 647
doPost(request, response)
method.Generally, all data passed should be in JSON format. In your case, it should read
data: {'obj' : data}
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
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