Subscribe / Unsubscribe Enewsletters | Login | Register

Pencil Banner

Jump into Java microframeworks, Part 3: Spark

Matthew Tyson | Jan. 8, 2016
An extra lightweight, flexible, and scalable architecture for single-page web apps.

Next, using the same process, add the Serialize Object jQuery plugin. This plugin will manage the process of converting the HTML form into a JSON format that the server can understand. (Recall that the addPerson() method from Listing 8 expects a JSON string.)

Finally, add a file called app.js into the same directory. As you can see in Listing 13, app.js contains simple controls for the template.html.

Listing 13. Custom JavaScript in app.js



App = {

		startup: function(){

			$("#addPersonButton").click(App.addPerson);

			App.loadPeople();

		},

		addPerson: function(){

			var person = $('#personForm').serializeObject();

			$.ajax({

		        url: '/person',

		        type: 'POST',

		        contentType: 'application/json',

		        data: JSON.stringify(person),

		        success: function(){

		        	App.loadPeople();

		        },

		        error: function(x){

		        	console.error("encountered a problem: ", x);

		        }

		    });

			return false;

		},

		loadPeople: function(){

			$.getJSON( "/people", function( data ) {

				  var items = [];

				  $.each( data, function( key, val ) {

				    items.push( "<li id='" + key + "'>" + val.firstName + " " + val.lastName + "</li>" );

				  });

				  $("#people").empty();

				  $("#people").html("<ul>"+items.join("")+"</ul>");

				});

		}

}

$( document ).ready(function() {

   App.startup();

});



app.js produces an App object, which contains methods we'll use to interact with server-side REST services.

Finally, we need to tell Spark about our /public directory. Do this by going to App.java, in the main() method, and adding the code from Listing 14, below. Be sure to update App.java before you define any routes! This will tell Spark to map the application's assets directory, allowing browser requests access to public resources like JavaScript files.

Listing 14. Mapping the public assets dir



public static void main( String[] args ){

    	Spark.staticFileLocation("/public");

		// ...



Completing the CRUD cycle

We defined addPerson at the beginning of this tutorial, so it's all set to be used by the App.addPerson() method. Next we'll create the /people GET endpoint for App.loadPeople.

Start by mapping the /people path in App.java, as shown in Listing 15.

Listing 15. People POST URL mapping



	Spark.get("/people", (req, res) -> { return controller.loadPeople(req.body()); });



Next add the loadPeople() method to the controller, as shown in Listing 16.

Listing 16. Controller.loadPeople()



	public String loadPeople(String body) {

		return mapper.toJson(dao.loadPeople());

	}



The loadPeople() method in Listing 16 uses Boon's JSON mapper to convert whatever dao.loadPeople returns into JSON. Note that we've also taken the request body as an argument. We won't do anything with it for now, but it's there if we need it later -- for example, if we wanted to add search parameters to the application.

 

Previous Page  1  2  3  4  5  6  7  8  Next Page 

Sign up for CIO Asia eNewsletters.