Reputation: 5454
I have a Spring MVC application using jQuery Datatables to render the data. Here are my classes and javascript code
Employee.java
public class Employee {
private int empId ;
private String firstName;
private String lastName ;
// getters and setters
}
EmployeeResponse.java
public class EmployeeResponse {
private List<Employee> empList ;
// getters and setters
}
EmployeeController.java
@Controller
@RequestMapping("/admin")
public class EmployeeController {
@RequestMapping(value = "/get-all-employee", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public EmployeeResponse getAllEmployee(HttpServletRequest request) {
EmployeeResponse response = new EmployeeResponse();
try {
response = getAllEmployeeList(); // returns response object
} catch (Exception e) {
logger.error("DCConsoleController::createNewStream exception: " + com.priceline.utils.StringUtils.getStackTrace(e));
return null;
}
return response ;
}
}
emp.jsp
<div class="row">
<table id="ldapStreamTable" class="table">
<thead>
<tr>
<th>Emp Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
</table>
</div>
emp.js
$(document).ready(function() {
var table = $('#appTable').DataTable( {
"sDom" : domSetting,
"oLanguage" : {
"sLengthMenu" : "_MENU_ records per page",
"sSearch" : "<span class='add-on'><i class='icon-search'></i></span>Search Application:",
"sZeroRecords" : "No matching records found",
},
"iDisplayLength" : 10,
"aLengthMenu" : [
[ 5, 10, 20, 25, 50, -1 ],
[ 5, 10, 20, 25, 50, "All" ] ],
"aaSorting" : [ [ 0, 'asc' ] ],
'sAjaxSource': '{context}/admin/get-all-employee',
[Pending here]
});
});
What should I do to get the response as json and apply/use render methods for each column to render the data into the table?
[Note: looks like I can't use aoColumns' with mData for each column because my json response is list of employee objects]
Update - 1: Sample json below
{"empList":[{"empId":3,"firstName":"Kiran","lastName":"Kumar"},{"empId":1,"firstName":"John","lastName":"Smith"},{"empId":0,"firstName":"Sachin","lastName":"Kumar"}]}
Upvotes: 1
Views: 10465
Reputation: 29683
I've kept your sample ajax
data in github
and gave it as a ajax
source. You keep that part to your method
which returns json
response, but instead of empList
as base root in json
response replace it with data
as I've done in the above github
json
file. Now apart from ajaxSource
you need to map columns
to your dataTables
as below:
"columns": [
{ "data": "empId"},//should match column value in json file
{ "data": "firstName"},//should match column value in json file
{ "data": "lastName"}//should match column value in json file
]
Upvotes: 3