Spring MVC AJAX web services Part 2, attack of the JSON post

Previously I covered how to create simple AJAX web services using Spring MVC and annotated controllers. This made it very easy to create robust services that automatically convert your java beans into JSON for easy consumption by your AJAX client. In this post, I’ll show how to use a simple javascript library to convert your HTML form into a JSON object that your Spring controller can consume and marshal to a java bean automagically.

Using this simple JS library coupled with jQuery you can easily create a JSON object by calling $(‘#formId’).serializeObject(); and pass that information using jQuery’s $.post or $.get methods.

<form id="deviceForm">
<input type="text" name="name"/>
<input type="text" name="manufacturer"/>
<input type="button" id="submit"/>
</form>
<script>
$('#submit').click(function() {
var deviceJSON = $('#deviceForm').serializeObject();
$.post("/devices/addDevice", deviceJSON, function(data) {
alert("callback");
});
}
</script>

All you need to do is change the method signature and annotations within your controller to let it know what type of object the JSON is supposed to be converted to.

@Controller
public class DeviceController {
@RequestMapping(value="/devices/byManufacturer", method=RequestMethod.GET)
@ResponseBody
public List<Device> getDevicesByManufacturer(@RequestParam String manufacturer) {
DeviceDAO dao = new DeviceDAO();
return dao.findByManufacturer(manufacturer);
}

@RequestMapping(value="/devices/addDevice", method=RequestMethos.POST)
@ResponseBody
public Device addDevice(@RequestBody Device toAdd) {
DeviceDAO dao = new DeviceDAO();
return dao.store(toAdd);
}
This entry was posted in Java, Javascript, jQuery, JSON, Programming, Spring and tagged , , , , , , . Bookmark the permalink.

One Response to Spring MVC AJAX web services Part 2, attack of the JSON post

  1. Pingback: Spring MVC AJAX web services | Cribbs Technologies

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>