Spring MVC Pagination dataTables

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:

Spring MVC Pagination dataTables

  • 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:

Spring MVC Pagination dataTables

  •  Please add below dependency in pom.xml file:

  •  Please copy below XML into your web.xml file

  •  Now create file name: dispatcher-servlet.xml inside WEB-INF folder and copy and paste below content:

  •  Create jsp folder inside WEB-INF folder
  • Create jsp file name: helloWorld.jsp and copy paste below code:

  •  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

  •  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:

  •  Create class name: Person.java inside com.javahonk.controller pakcage and copy paste below content in it:

  •  Create class name: PersonJsonObject.java inside com.javahonk.controller pakcage and copy paste below content in it:

  • 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:

Spring MVC Pagination dataTables

  •  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…

Spring MVC Pagination dataTables

  • Search filter screen:

Spring MVC Pagination dataTables

download Download Project:  SpringPaginationDataTables

That’s it Spring MVC Pagination dataTables completed

35 thoughts on “Spring MVC Pagination dataTables

  1. 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 .

  2. 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.

  3. 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.

  4. 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 .

  5. 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

  6. 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.

  7. 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.

  8. 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.

  9. 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

  10. 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.

  11. 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;
    }

  12. @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

  13. 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.

  14. 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.

Leave a Reply

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