Friday, January 25, 2013

Spring MVC v3.2 Json Response

1) example to put a list of userid in a combobox via ajax call, and spring mvc returns json data directly


$.ajax({
type : 'POST',
url : "users.do",
success : function(data) {
var userid = data[0].userid;
console.info("2-------------" + userid);
$(data).each(function() {
var option = $('<option/>');
option.attr('value', this.userid).text(this.userid);
$("#combobox").append(option); // loop response data and add option to combobox
}) },
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
dataType : "json"
});


2) use datatables jquery plugin to show data in a table on front end, spring mvc returns json data directly

var oTable = $('#myDataTable').dataTable({
"bProcessing" : true,
"bDestroy" : true,
"sAjaxSource" : 'users.do',
"sAjaxDataProp" : "",
//"bFilter":false,
"aoColumns" : [ {
"mData" : "userid"
}, {
"mData" : "password"
}, {
"mData" : "timeStamp"
} ],
"sPaginationType" : "full_numbers",
"aLengthMenu" : [ [ 4, 10, 20, -1 ], [ 4, 10, 20, "All" ] ],
"iDisplayLength" : 4
});


<table id="myDataTable" cellpadding="0" cellspacing="0" border="0" class="display datatable"> <thead> <tr> <th width="20%">userid</th> <th width="20%">password</th> <th width="20%">time</th> </tr> </thead> <tbody> </tbody>
</table>

3) java code in servlet


@RequestMapping(value = "/users", produces = "application/json")
public @ResponseBody List<Account> showUser() {
return accountService.getAccounts();
}

From the source code, we can see it just returns a pure java list, the @ResponseBody annotation and produces = "application/json" will help to convert java objects to json string.


4) need add jackson dependency

<!-- support json response --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> </dependency> <!-- End support json response -->

otherwise, you may encounter 406 (Not Acceptable)

5) This is the example data returned by spring mvc

[{"userid":"a1","password":"a","timeStamp":1359012297000,"checked":0}, {"userid":"abgh0","password":"dddd0","timeStamp":1359012165000,"checked":1}, {"userid":"abgh1","password":"dddd1","timeStamp":1359012165000,"checked":1}, {"userid":"abgh10","password":"dddd10","timeStamp":1359012165000,"checked":1}]



1 comment: