0

I have the below ajax call to a servlet.

$.ajax({ 
type: "post",
url: registersubmit.RegisterServlet.json,
dataType: "json",   
data:$('#registrationForm').serialize(),          
success: function(msg) {  
           //   alert(msg.data);
           alert('success'+msg.message2);     
},
error: function (xhr, ajaxOptions, thrownError){
         alert('HAI');
         alert('BYE');
}  
});

May I know how we can consume the json object in the servlet

Thanks, Balaji.

Abubakkar
  • 15,488
  • 8
  • 55
  • 83
balaji
  • 774
  • 1
  • 16
  • 42

2 Answers2

1

You can use GSON library a Java library that can be used to convert JSON representation into Java objects and vice versa

Abubakkar
  • 15,488
  • 8
  • 55
  • 83
  • Whilst this does indeed answer OP's concrete question as stated in the title, this does not solve OP's concrete problem as shown in the code snippet at all. – BalusC Oct 22 '12 at 01:50
1

There's a huge misunderstanding here. The way how you sent the ajax request doesn't end up in a JSON object in the server side at all. All the data is just available by request.getParameter() the usual way. The $.serialize() merely collects all input values of the form into a JSON object which is in turn behind the scenes by $.ajax encoded as HTTP query string the usual way. The JSON object is merely an intermediary format which allows you to very easily submit the entire form using $.ajax.

So, the data of

<form id="registrationForm" ...>
    <input name="foo" ... />
    <input name="bar" ... />
    <input name="baz" ... />
</form>

can in the servlet just be collcted exactly the same way as if it were a synchronous (a regular) submit

String foo = request.getParameter("foo");
String bar = request.getParameter("bar");
String baz = request.getParameter("baz");
// ...

Please note that the dataType option instructs the jQuery $.ajax() as which data type the response should be treated. It has totally no relationship with how the data is been sent by the request. It's just been sent as HTTP request parameters the usual way. See also $.ajax() documentation.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555