Passing data between a JSP page and servlet using JSON and JQuery (part 1)

JavaScript Object Notation, or JSON for short, is a human-readable and compact way to exchange data between systems.  JSON has been referred to as a fat-free alternative to XML.

There are lots of websites that explain the pros and cons to using XML vs. JSON so I won’t go into that here.  Rather, I’ll give a brief but complete example of how to use JSON to communicate between a web page and a servlet.

Since I like to keep things simple, I’ll use the JSON.simple Java API in this example. 

Here’s example code for the submit button that you can add to your web form.  This will call the submitForm() JavaScript function when clicked:

<input type="submit" name="submit" value="Submit" onclick="return submitForm(this, event);"> 

Here’s the JavaScript function that your web page will call to submit the form.  You can embed this function directly in the web page or include it as a separate .js file.  This is just the shell of the actual function – I’ll explain the rest of the code below as we fill in the rest of the details.

function submitForm(thisObj, thisEvent) {
   return false;  // prevents the page from refreshing before JSON is read from server response
}

Now we’ll add some code to set some local JavaScript variables with values from the web page form:

var ecoStatus = $('input[name=status]:checked').val(); // status is a radio button
var emailName= $('#email').val();                      // email is an input field
var exportFormat2D= $('#export_2d').val();             // export_2d is a select element
var exportFormat3D= $('#export_3d').val();             // export_3d is a select element
var exportSupplier= $('#supplier').val();              // supplier is an input field
var fromDrawingNumber= $('#old_number').val();         // old_number is an input field
var partNumbers= $('#part_numbers').val();             // part_numbers is a textarea
var toDrawingNumber= $('#new_number').val();           // new_number is an input field

 Now we’ll create the JSON data object and fill it with the values contained in the variables:

var jsonDataObject = new Object();
jsonDataObject.ecoStatus = ecoStatus;
jsonDataObject.emailName = emailName;
jsonDataObject.exportFormat2D = exportFormat2D;
jsonDataObject.exportFormat3D = exportFormat3D;
jsonDataObject.exportSupplier = exportSupplier;
jsonDataObject.fromDrawingNumber = fromDrawingNumber;
jsonDataObject.partNumbers = partNumbers;
jsonDataObject.toDrawingNumber = toDrawingNumber;

Now we need to convert the jsonDataObject to string format in preparation for sending it to the servlet using an HTTP request:

var jsonData = JSON.stringify(jsonDataObject);

 Now it’s time to send the stringified JSON data object to the server.  There’s a lot going on in these 3 lines so I’ll give a brief explanation for each segment:

  • $.getJSON(); – this is a Jquery command to load JSON-encoded data from the server using a GET HTTP request.
  • exportservlet – the name of the servlet as registered in the web.xml file on your web server
  • {action:”export”, json:jsonData} – arguments passed to the servlet as objects
  • function() – the callback function that’s executed when data is returned from the server.
  • data – the JSON object returned from the server
  • data.message – the return message from the server
  • alert(); – an example of calling a local JavaScript function from within the callback function().  This will display a dialog showing a message from the server.
  • $(‘#return_message’).html(data.message); – an example of setting an HTML element on the web page with id=”return_message” with the value contained by data.message.
$.getJSON("exportservlet", {action:"export",json:jsonData}, function(data) {
   alert(data.message);
   $('#return_message').html(data.message);
});

 Here’s what the finished function looks like when we put together everything shown above:

function submitForm(thisObj, thisEvent) {
   var ecoStatus = $('input[name=status]:checked').val(); // status is a radio button
   var emailName= $('#email').val();                      // email is an input field
   var exportFormat2D= $('#export_2d').val();             // export_2d is a select element
   var exportFormat3D= $('#export_3d').val();             // export_3d is a select element
   var exportSupplier= $('#supplier').val();              // supplier is an input field
   var fromDrawingNumber= $('#old_number').val();         // old_number is an input field
   var partNumbers= $('#part_numbers').val();             // part_numbers is a textarea
   var toDrawingNumber= $('#new_number').val();           // new_number is an input field

   var jsonDataObject = new Object();
   jsonDataObject.ecoStatus = ecoStatus;
   jsonDataObject.emailName = emailName;
   jsonDataObject.exportFormat2D = exportFormat2D;
   jsonDataObject.exportFormat3D = exportFormat3D;
   jsonDataObject.exportSupplier = exportSupplier;
   jsonDataObject.fromDrawingNumber = fromDrawingNumber;
   jsonDataObject.partNumbers = partNumbers;
   jsonDataObject.toDrawingNumber = toDrawingNumber;

   // turn the jsonData object into a string so it can be passed to the servlet
   var jsonData = JSON.stringify(jsonDataObject);

   $.getJSON("exportservlet", {action:"export",json:jsonData}, function(data) {
      alert(data.message);
      $('#return_message').html(data.message);
   });
 
   return false;  // prevents the page from refreshing before JSON is read from server response
}

 That’s it for part 1.  In part 2 I’ll show how to handle the server-side processing using a Servlet.

11 thoughts on “Passing data between a JSP page and servlet using JSON and JQuery (part 1)

  1. Pingback: Passing data between a JSP page and servlet using JSON and JQuery (part 2) | Chilled Java

  2. Woah this weblog is extremely good i like reading the articles you write. Remain up the great do the job! You already know, a lot of people are generally seeking circular for this details, you are able to help them enormously.

    Like

  3. Hi
    I followed the instructions in your article as best as I could. I would like to get the JSON response back in my calling page. On this calling page, I submit form data as JSON, using the simple JSON API just I submitted data to the servlet (in JSON format).
    My server response contains some results of a lookup from a database. I would like that sent back to the calling page. I am not clear how to do that. Any help is appreciated.

    Like

  4. I have followed your instruction and code too.. But when i click on submit button no action is done. I’m very new to this field. Please help me out here.

    Like

Leave a comment