Reputation: 29
I have the following javascript code:
var data = {message:"Hi"}
var sendJson = function (){
alert(data);
$.ajax({
url:"./jsonTest",
data: data,
contentType:"application/json",
type:"post",
dataType:"json"
}).success(function(reply) {
alert("successful");
});
}
How can I fetch the JSON object on my servlet?
I was previously trying to get it using
request.getParameter("data")
and trying to convert it to a JsonObject, but I kept getting null
.
Upvotes: 1
Views: 9569
Reputation: 7004
@Kebs,
If this isn't figured out yet .. You can find the answer here :)
Upvotes: 1
Reputation: 116620
You might want to check out JAX-RS containers (Jersey) which build on top of basic Servlet API, but make it much more convenient to get data binding for JSON.
But if you must use raw Servlet API, then POST contents will be available through request object; get the InputStream, and use a JSON library like Jackson to bind to object:
MyBean bean = new ObjectMapper().readValue(httpRequest.getInputStream(), MyBean.class);
and similarly if you need to return a JSON object, do the reverse:
objectMapper.writeValue(httpResponse.getOutputStream(), resultObject);
Upvotes: 0
Reputation: 31
In case data
is object it will be transformed to request parameter string like
pameterName1=value1&pameterName2=value2
and you can get it by using
request.getParameter("pameterName1");
Upvotes: 0
Reputation: 125
try the line below. data is only the javascript variable but jquery will put the message member in the URL params instead of data.
request.getParameter("message");
Upvotes: 0