Saturday, January 4, 2014

JQuery, JSON, restful services and Spring MVC - a simple introduction

Knowing how jQuery and css works in the context of a web page is a must-have skill for any web developer. I recently came across a tutorial which has a nice usage of jQuery in its page.  This is the link:

http://codetutr.com/2013/04/09/spring-mvc-easy-rest-based-json-services-with-responsebody/

The page looks like this: 




Here's the page source, with my comments, (I'll use a "//", although it's not valid for html - and supplements the author's own comments in the jQuery). 

// import the jstl taglib
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

// import spring form tag library
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<!DOCTYPE HTML>
<html>
  <head>
    <title>Spring MVC - Ajax</title>

// import jquery library
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <style>

// css - define the background / font for the body
    body { background-color: #eee; font: helvetica; }'

// define container properties
    #container { width: 500px; background-color: #fff; margin: 30px auto; padding: 30px; border-radius: 5px; box-shadow: 5px; }

// "green" class
    .green { font-weight: bold; color: green; }
    .message { margin-bottom: 10px; }

// set up error display
    label { width:70px; display:inline-block;}
    .hide { display: none; }
    .error { color: red; font-size: 0.8em; }
    </style>
  </head>
  <body>
<div id="container">
<h1>Person Page</h1>
<p>This page demonstrates Spring MVC's powerful Ajax functionality. Retrieve a
random person, retrieve a person by ID, or save a new person, all without page reload.
</p>
<h2>Random Person Generator</h2>

// submit to restful service at "person/random" - see jQuery script 
<input type="submit" id="randomPerson" value="Get Random Person" /><br/><br/>

// div to hold the person returned - written to by jQuery code below
<div id="personResponse"> </div>
<hr/>


<h2>Get By ID</h2>

// form to retrieve by id
<form id="idForm">
<div class="error hide" id="idError">Please enter a valid ID in range 0-3</div>
<label for="personId">ID (0-3): </label><input name="id" id="personId" value="0" type="number" />
<input type="submit" value="Get Person By ID" /> <br /><br/>

// area to show person retrieved
<div id="personIdResponse"> </div>
</form>
<hr/>

// new person form
<h2>Submit new Person</h2>
<form id="newPersonForm">
<label for="nameInput">Name: </label>
<input type="text" name="name" id="nameInput" />
<br/>
<label for="ageInput">Age: </label>
<input type="text" name="age" id="ageInput" />
<br/>
<input type="submit" value="Save Person" /><br/><br/>
<div id="personFormResponse" class="green"> </div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {

// Random Person AJAX Request
$('#randomPerson').click(function() {

// this is an ajax call - will make a request like this:
// GET /spring-mvc-ajax-master/api/person/random
// Accept: application/json, text/javascript, */*; q=0.01

$.getJSON('${pageContext.request.contextPath}/api/person/random', function(person) {

// set the fields in the web page based on the response
$('#personResponse').text(person.name + ', age ' + person.age);
});
});

// Request Person by ID AJAX

// called on idForm click
$('#idForm').submit(function(e) {

// grab the person's id
var personId = +$('#personId').val();

// validate it
if(!validatePersonId(personId)) 

// invalid - don't propagate the submit and exit by returning false
return false;

// Get the person, this time doing  a ".get". It still receives JSON back,
// although the accept header doesn't specify JSON
// On the wire, it looks like this:

// GET /spring-mvc-ajax-master/api/person/3
// Accept: */*

// Apparently the Jackon handler defaults to JSON,
// Therefore the response can be parsed in the same
// manner as in the above method.
$.get('${pageContext.request.contextPath}/api/person/' + personId, function(person) {
$('#personIdResponse').text(person.name + ', age ' + person.age);
});
e.preventDefault(); // prevent actual form submit
});


// Save Person AJAX Form Submit
$('#randomPerson').click(function() {
$.getJSON('${pageContext.request.contextPath}/api/person/random', function(person) {
$('#personResponse').text(person.name + ', age ' + person.age);
});
});
$('#newPersonForm').submit(function(e) {
// will pass the form data using the jQuery serialize function
// Because it's a post, the data will be passed in the body.

// The serialize function creates a standard URL-encoded string:
// e.g: "name=Tom+Jones&age=57"
// The $(this) must refer to the form which was submitted by clicking on the submit button.

$.post('${pageContext.request.contextPath}/api/person', $(this).serialize(), function(response) {
$('#personFormResponse').text(response);
});
e.preventDefault(); // prevent actual form submit and page reload
});
});

// Neat function which uses label properties as a method to activate them, e.g. show/hide errors.
function validatePersonId(personId) {
console.log(personId);
if(personId === undefined || personId < 0 || personId > 3) {
$('#idError').show();
return false;
}
else {
$('#idError').hide();
return true;
}
}
</script>
  </body>
</html>



No comments:

Post a Comment