1

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.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
Kebs
  • 29
  • 1
  • 4

4 Answers4

1

@Kebs,

If this isn't figured out yet .. You can find the answer here :)

Community
  • 1
  • 1
Shrayas
  • 6,784
  • 11
  • 37
  • 54
0

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"); 
joelbyler
  • 125
  • 3
0

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");

Alenka
  • 31
  • 3
  • I tried it and I am still getting null. Do I need to enable something on server side? – Kebs Aug 24 '11 at 13:42
  • It seems you use inappropriate `content-type` parameter. I've just commented `contentType:"application/json"` and parameter's passed to servlet. I think it's better to use $.get() or $.post() jQuery function – Alenka Aug 24 '11 at 18:58
0

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);

StaxMan
  • 113,358
  • 34
  • 211
  • 239