Spring MVC Pagination dataTables
There are many plug-in available to create pagination in MVC based web application. In this demo we will use DataTables plug-in for JQuery to create pagination in our Spring MVC based application. DataTable plug-in is very customizable and easy to use plug-in with minimal coding. For information about this plug-in please visit their web site here. Below are links of other pagination tutorial we had written before:
In below example you will see sample data that has been built in controller as JSON format and pass back to the DataTables to create pagination. In real time you could directly fetch data from the data base and if your data size is very large you could directly pass current position and page size to fetch data for the page.
Below are needed:
- Eclipse 3.2 or above (Download from here) – Note for this demo we have used eclipse Kepler
- JDK 1.6 or above (Download from here )
- Tomcat 6 or above (Please follow link to install and configure tomcat in eclipse: Configure and Run Tomcat server in eclipse )
- Spring version 4.0.3.RELEASE (Dependency already included in pom.xml)
- Maven 3.0.4
- Google gson-2.2.2 jar which we have used to convert object in JSON format (Dependency already included in pom.xml)
- Note: All codes are available for download in the bottom of the page
- DataTables CSS,JS which you can get it directly form its site here (Links are already include in jsp page you don’t need to download anything)
- JQuery js file (Links are already include in jsp page you don’t need to download anything)
After all set up and configuration you will see below screen:
- Create maven project name SpringPaginationDataTables in eclipse (Please use this link if you are not familiar how to create maven project in eclipse: Create maven Project Eclipse)
- Below shows project structure:
- Please add below dependency in pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javahonk</groupId> <artifactId>SpringPaginationDataTables</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringPaginationDataTables Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <spring.version>4.0.3.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> </dependencies> <build> <finalName>SpringPaginationDataTables</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.0</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> </project>
- Please copy below XML into your web.xml file
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.web</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/dispatcher-servlet.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>helloWorld.web</welcome-file> </welcome-file-list> </web-app>
- Now create file name: dispatcher-servlet.xml inside WEB-INF folder and copy and paste below content:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.javahonk.controller" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
- Create jsp folder inside WEB-INF folder
- Create jsp file name: helloWorld.jsp and copy paste below code:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Spring pagination using data tables</title> <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.0/css/jquery.dataTables.css"> <script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript" src="//cdn.datatables.net/1.10.0/js/jquery.dataTables.js"></script> <script type="text/javascript"> //Plug-in to fetch page data jQuery.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings ) { return { "iStart": oSettings._iDisplayStart, "iEnd": oSettings.fnDisplayEnd(), "iLength": oSettings._iDisplayLength, "iTotal": oSettings.fnRecordsTotal(), "iFilteredTotal": oSettings.fnRecordsDisplay(), "iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ), "iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength ) }; }; $(document).ready(function() { $("#example").dataTable( { "bProcessing": true, "bServerSide": true, "sort": "position", //bStateSave variable you can use to save state on client cookies: set value "true" "bStateSave": false, //Default: Page display length "iDisplayLength": 10, //We will use below variable to track page number on server side(For more information visit: http://legacy.datatables.net/usage/options#iDisplayStart) "iDisplayStart": 0, "fnDrawCallback": function () { //Get page numer on client. Please note: number start from 0 So //for the first page you will see 0 second page 1 third page 2... //Un-comment below alert to see page number //alert("Current page number: "+this.fnPagingInfo().iPage); }, "sAjaxSource": "springPaginationDataTables.web", "aoColumns": [ { "mData": "name" }, { "mData": "position" }, { "mData": "office" }, { "mData": "phone" }, { "mData": "start_date" }, { "mData": "salary" }, ] } ); } ); </script> </head> <body> <form:form action="" method="GET"> <h2 >Spring MVC pagination using data tables<br><br></h2> <table width="70%" style="border: 3px;background: rgb(243, 244, 248);"><tr><td> <table id="example" class="display" cellspacing="0" width="100%"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Phone</th> <th>Start Date</th> <th>Salary</th> </tr> </thead> </table> </td></tr></table> </form:form> </body> </html>
- Please note: To use DataTable you will have to add below css,js in your jsp file shown below for more information go to datatables site here
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.0/css/jquery.dataTables.css"> <script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript" src="//cdn.datatables.net/1.10.0/js/jquery.dataTables.js"></script>
- Create package name com.javahonk.controller inside src/main/java folder
- Create class name: SpringMVCController.java inside com.javahonk.controller pakcage and copy paste below content in it:
package com.javahonk.controller; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @Controller public class SpringMVCController { @RequestMapping(value = "/helloWorld.web", method = RequestMethod.GET) public String printWelcome(@ModelAttribute("person") Person person, BindingResult result,ModelMap model, HttpServletRequest request, HttpServletResponse response) { return "helloWorld"; } @RequestMapping(value = "/springPaginationDataTables.web", method = RequestMethod.GET, produces = "application/json") public @ResponseBody String springPaginationDataTables(HttpServletRequest request) throws IOException { //Fetch the page number from client Integer pageNumber = 0; if (null != request.getParameter("iDisplayStart")) pageNumber = (Integer.valueOf(request.getParameter("iDisplayStart"))/10)+1; //Fetch search parameter String searchParameter = request.getParameter("sSearch"); //Fetch Page display length Integer pageDisplayLength = Integer.valueOf(request.getParameter("iDisplayLength")); //Create page list data List<Person> personsList = createPaginationData(pageDisplayLength); //Here is server side pagination logic. Based on the page number you could make call //to the data base create new list and send back to the client. For demo I am shuffling //the same list to show data randomly if (pageNumber == 1) { Collections.shuffle(personsList); }else if (pageNumber == 2) { Collections.shuffle(personsList); }else { Collections.shuffle(personsList); } //Search functionality: Returns filtered list based on search parameter personsList = getListBasedOnSearchParameter(searchParameter,personsList); PersonJsonObject personJsonObject = new PersonJsonObject(); //Set Total display record personJsonObject.setiTotalDisplayRecords(500); //Set Total record personJsonObject.setiTotalRecords(500); personJsonObject.setAaData(personsList); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json2 = gson.toJson(personJsonObject); return json2; } private List<Person> getListBasedOnSearchParameter(String searchParameter,List<Person> personsList) { if (null != searchParameter && !searchParameter.equals("")) { List<Person> personsListForSearch = new ArrayList<Person>(); searchParameter = searchParameter.toUpperCase(); for (Person person : personsList) { if (person.getName().toUpperCase().indexOf(searchParameter)!= -1 || person.getOffice().toUpperCase().indexOf(searchParameter)!= -1 || person.getPhone().toUpperCase().indexOf(searchParameter)!= -1 || person.getPosition().toUpperCase().indexOf(searchParameter)!= -1 || person.getSalary().toUpperCase().indexOf(searchParameter)!= -1 || person.getStart_date().toUpperCase().indexOf(searchParameter)!= -1) { personsListForSearch.add(person); } } personsList = personsListForSearch; personsListForSearch = null; } return personsList; } private List<Person> createPaginationData(Integer pageDisplayLength) { List<Person> personsList = new ArrayList<Person>(); for (int i = 0; i < 1; i++) { Person person2 = new Person(); person2.setName("John Landy"); person2.setPosition("System Architect"); person2.setSalary("$320,800"); person2.setOffice("NY"); person2.setPhone("999999999"); person2.setStart_date("05/05/2010"); personsList.add(person2); person2 = new Person(); person2.setName("Igor Vornovitsky"); person2.setPosition("Solution Architect"); person2.setSalary("$340,800"); person2.setOffice("NY"); person2.setPhone("987897899"); person2.setStart_date("05/05/2010"); personsList.add(person2); person2 = new Person(); person2.setName("Java Honk"); person2.setPosition("Architect"); person2.setSalary("$380,800"); person2.setOffice("NY"); person2.setPhone("1234567890"); person2.setStart_date("05/05/2010"); personsList.add(person2); person2 = new Person(); person2.setName("Ramesh Arrepu"); person2.setPosition("Sr. Architect"); person2.setSalary("$310,800"); person2.setOffice("NY"); person2.setPhone("4654321234"); person2.setStart_date("05/05/2010"); personsList.add(person2); person2 = new Person(); person2.setName("Bob Sidebottom"); person2.setPosition("Architect"); person2.setSalary("$300,800"); person2.setOffice("NJ"); person2.setPhone("9876543212"); person2.setStart_date("05/05/2010"); personsList.add(person2); } for (int i = 0; i < pageDisplayLength-5; i++) { Person person2 = new Person(); person2.setName("Zuke Torres"); person2.setPosition("System Architect"); person2.setSalary("$320,800"); person2.setOffice("NY"); person2.setPhone("999999999"); person2.setStart_date("05/05/2010"); personsList.add(person2); } return personsList; } }
- Create class name: Person.java inside com.javahonk.controller pakcage and copy paste below content in it:
package com.javahonk.controller; public class Person { private String name; private String position; private String office; private String phone; private String start_date; private String salary; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getOffice() { return office; } public void setOffice(String office) { this.office = office; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getStart_date() { return start_date; } public void setStart_date(String start_date) { this.start_date = start_date; } public String getSalary() { return salary; } public void setSalary(String salary) { this.salary = salary; } }
- Create class name: PersonJsonObject.java inside com.javahonk.controller pakcage and copy paste below content in it:
package com.javahonk.controller; import java.util.List; public class PersonJsonObject { int iTotalRecords; int iTotalDisplayRecords; String sEcho; String sColumns; List<Person> aaData; public int getiTotalRecords() { return iTotalRecords; } public void setiTotalRecords(int iTotalRecords) { this.iTotalRecords = iTotalRecords; } public int getiTotalDisplayRecords() { return iTotalDisplayRecords; } public void setiTotalDisplayRecords(int iTotalDisplayRecords) { this.iTotalDisplayRecords = iTotalDisplayRecords; } public String getsEcho() { return sEcho; } public void setsEcho(String sEcho) { this.sEcho = sEcho; } public String getsColumns() { return sColumns; } public void setsColumns(String sColumns) { this.sColumns = sColumns; } public List<Person> getAaData() { return aaData; } public void setAaData(List<Person> aaData) { this.aaData = aaData; } }
- Now lets run this set up in tomcat server. If you haven’t done tomcat set up in eclipse yet please use this link: Configure and Run Tomcat server in eclipse. Now right click project –>Run As –> Run on server as below:
- Finally you will see below pagination screen with data, click on column name to sort it also you could search data, and configure number of entries etc…
- Search filter screen:
Download Project: SpringPaginationDataTables
That’s it Spring MVC Pagination dataTables completed
Could you please explain how to pass current position and page size to fetch data for the page?
How can i add export to excel, pdf , and csv. I saw tools on data table website but it was bit tough to understand . can you plz explain to add the that in my project .
Hi, it is really great example, and it is working perfectly, but I want to add link to jsp page in row name, to show every person in new page. Do you know how I can do that? Thanks in advance.
You could add link to JSP page in row name adding static page link with href attribute
Hi Sir,
Could i know how can i implement this in Spring-hibernate-database integration part, since i am new to these. kinldly help me please.
Thanks.
Aravind – For spring and hibernate integration please use this tutorial and once you get data from the database populate it in SpringMVCController.java class. As you will see for this tutorial we are populating static data so in place of static data in for loop use your dynamic data from database.
getting some errors while changing page size and search option not working
I have updated the code and now you have all variable available on server side.
This is Client side pagination .can you please change to server side pagination . problem with this is that it will work on few hundreds rows only. if have million rows that it will stuck .
I have changed this to server side pagination. Now you could handle everything on server side and its good for large data set.
Please tell mi how to make above project as server side pagination
Great article, please add the below dependency if the example do not work for the http dependency in pom.xml file as below.
javax.servlet
javax.servlet-api
3.0.1
Thanks,
Taleb
Thanks. Dependency added.
Excellent example, it’s been helpful to me. I see one bug: the pageNumber calculation uses a hardcoded value of 10, which means it’s only accurate when the DataTable displays ten rows per page. To be accurate for other table sizes, the pageNumber calc should use pageDisplayLength (determined by the iDisplayLength param) instead of 10.
Thanks very much.
Hi,
Thanks for this tutorial, I will appreciate if you can integrate mysql database instead of static data, for example I got confused how this function will be :
private List createPaginationData(Integer pageDisplayLength) {
Thanks, your help is appreciated.
To integrate database you could take reference form this tutorial http://javahonk.com/spring-jdbctemplate-calling-stored-procedure-in-out-parameter/
Hi i’m also confuse – here is my code
private List createPaginationData(Integer pageDisplayLength) {
List employee = serviceDao.getCurrentEmployee();
return employee;
}
Can you tell me how can i reDraw this Table..
Actually my Requirements says , i have a Search Criteria and on Click of Search it will go to DB fetch the Data and redraw the Table ….i Googled a lot but people says i need to redraw using fnDraw().. but i didn’t get this thing ….
Hope you understand my requirement….
As you see in the code everything has been handled on server side. So on click Search button you have to refresh the data that’s it.
Hi Java Honk,
Firstly thank you for providing the excellent example. I could make the pagination, Search all feature done but I am not able to sort for the particular column. How can I get the Indication to the controller about the column sorting. For example I am expecting something like
Sting sortType = request.getParameter(“name”);
sortType // asc / desc
so based on that I can sort the whole Person object.
Highly appreciate your help!!
Thanks & Regards
Divya
DataTables already provides default sorting on data display if you want to customize it please have a look on this: DataTables sorting.
Thanks a lot
This is a great tutorial.
I need to be able to add and delete new records in the datatables, I wonder if this is doable based on this example.
Thanks in advance.
Surely you can do it.
Could you please provide some key code lines? I seriously need it. Thanks a lot!
Also, could this be made a HTML5 compliant? Many thanks.
Its very good example! Here am posting a sample code for implementing server side pagination and sorting using the Spring MVC+ jquery datatables + pracle, i hope this can help somebody :
@RequestMapping(value = “/bjiListJsonAjax.web”, method = RequestMethod.GET, produces = “application/json”)
public @ResponseBody
String getUserList(HttpServletRequest request, HttpServletResponse response) {
Integer orderBy = 1;
String sortBy = “asc”;
//Fetch the orderby column value
//here we can get the column index value from the datatable it should be starting from 0, in this example am using oracle so that i have increased by one when sending to SQL
if (request.getParameter(“iSortCol_0”) != null) {
orderBy = Integer.valueOf(request.getParameter(“iSortCol_0”));
orderBy = orderBy + 1;
}
//Fetch the sort order either asc or desc
if (request.getParameter(“sSortDir_0”) != null) {
sortBy = request.getParameter(“sSortDir_0”);
}
//Fetch current page number
Integer pageNumber = 0;
if (null != request.getParameter(“iDisplayStart”)) {
pageNumber = (Integer
.valueOf(request.getParameter(“iDisplayStart”)) / 10) + 1;
}
//Service call for getting total count of the records
int noOfRecords = batchJobInstanceService.getCountOfBatchJonInstances();
//Fetch records per page
Integer pageDisplayLength = Integer.valueOf(request.getParameter(“iDisplayLength”));
//Driving pagination start and end position of the SQL
int startIndex = (pageNumber – 1) * pageDisplayLength;
int endIndex = pageNumber * pageDisplayLength;
//This pojo class will holing all attributes of pagination and sorting
Page page = new Page();
page.setEndIndex(startIndex);
page.setEndIndex(endIndex);
page.setOrderBy(orderBy);
page.setSortBy(sortBy);
//Service call for fetching actual data
List bjeList = batchJobInstanceService
.getListOfBatchJonInstances(page);
BatchJobInstanceJson batcInstanceJson = new BatchJobInstanceJson();
batcInstanceJson.setiTotalDisplayRecords(noOfRecords);
batcInstanceJson.setiTotalRecords(noOfRecords);
batcInstanceJson.setAaData(bjeList);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonStringValue = gson.toJson(batcInstanceJson);
return jsonStringValue;
}
There was one typo in my previous comment it should be Spring MVC+ jquery datatables + oracle
i am need editable datatable and in backend spring mvc.do you have any example
It not download
Please don’t click down arrow image but click the link after download word
When i click to header but column is not order! Please help me!
@RequestMapping(value = “/pagging.json”, method=RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String springPaginationDataTables(HttpServletRequest request){
logger.info(“request recieved”);
int displayLength = Integer.valueOf(request.getParameter(“iDisplayLength”));
int displayStart = Integer.valueOf(request.getParameter(“iDisplayStart”));
int sEcho = Integer.valueOf(request.getParameter(“sEcho”));
List se_req_List = seRequestService.getCertainRequests(displayStart,displayLength);
RequestDisplayJsonBean dispJsonBean = new RequestDisplayJsonBean();
int total_requests = seRequestService.getRowCountSE_table();
dispJsonBean.setiTotalDisplayRecords(total_requests);
dispJsonBean.setiTotalRecords(total_requests);
dispJsonBean.setsEcho(sEcho);
dispJsonBean.setAaData(se_req_List);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json=gson.toJson(dispJsonBean);
logger.info(“jason Objects: “+json);
return json;
}
$(document).ready(function() {
$(“#allrequest_disp_table”).dataTable({
“bProcessing”: true,
“bServerSide”: true,
“searching”: false,
“ordering”: false,
//bStateSave variable you can use to save state on client cookies: set value “true”
“bStateSave”: false,
//Default: Page display length
“iDisplayLength”: 10,
//We will use below variable to track page number on server side(For more information visit: http://legacy.datatables.net/usage/options#iDisplayStart)
“iDisplayStart”: 0,
“sEcho”:1,
“fnDrawCallback”: function () {
},
“sAjaxSource”: “pagging.json”,
“aoColumns”: [
{ “mData”: “se_request_id” },
{ “mData”: “fngrprnt” },
{ “mData”: “prev_carrier” },
{ “mData”: “prev_country” },
{ “mData”: “requester_id” },
{ “mData”: “reviewer_id” },
]
});
});
//Plug-in to fetch page data
jQuery.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
{
return {
“iStart”: oSettings._iDisplayStart,
“iEnd”: oSettings.fnDisplayEnd(),
“iLength”: oSettings._iDisplayLength,
“iTotal”: oSettings.fnRecordsTotal(),
“iFilteredTotal”: oSettings.fnRecordsDisplay(),
“iPage”: oSettings._iDisplayLength === -1 ?
0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
“iTotalPages”: oSettings._iDisplayLength === -1 ?
0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
};
};
This is my code.. When I am running this code, I cannot get the response from tomcat server. Please help
Please tell me how to have dynamic headers for the table. Because in this example aoColumns is set as static. I need that to be coming from the controller.
sorting (order ) is not working. When I click column, it is changing, however it is ordering in acs or desc. Can you please help?
I have not changed anything, downloaded your code and hosted on tomcat.
Hi , everything working perfectly but how to give links to update and delete for that particular row based on id ?.. it is possible from this project?….