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.

4 Answers 4

1

@Kebs,

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for that :) Ill be trying this ASAP. :)
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"); 

Comments

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

2 Comments

I tried it and I am still getting null. Do I need to enable something on server side?
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
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.