lunes, 24 de abril de 2017

How to use Jquery datatable in Spring MVC

Creating a table data along with features like pagination, filtering the records, sorting, no of records to show etc. is a challenger job for developers because it involves lot of designs and coding. But now it becomes very easy to develop with the help of jQuery datatable plugin. In this post we will show how to use jQuery datatable in Spring MVC 4 application.

Required Software to Run Example:
  • Java 7
  • Netbeans
  • Maven
  • MySQL
Project Structure in Netbeans

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">



        <!-- Spring -->
        <!-- Jackson -->

POJO Class used in Example
package com.rolandopalermo.domain;

import com.rolandopalermo.util.EmployeeStatus;
import com.rolandopalermo.util.JsonConverter;

 * @author rolan
public class Employee implements Serializable {

    private int id;
    private String name;
    private String surname;
    private int age;
    private String address;
    private EmployeeStatus status;

    public Employee(int id, String name, String surname, int age, String address, EmployeeStatus status) { = id; = name;
        this.surname = surname;
        this.age = age;
        this.address = address;
        this.status = status;

    public int getId() {
        return id;

    public void setId(int id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String getSurname() {
        return surname;

    public void setSurname(String surname) {
        this.surname = surname;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public String getAddress() {
        return address;

    public void setAddress(String address) {
        this.address = address;
    public EmployeeStatus getStatus() {
        return status;

    public void setStatus(EmployeeStatus status) {
        this.status = status;

    public String toString() {
        String json = JsonConverter.INSTANCE.asJsonString(this);
        return json;

Spring MVC Controller
package com.rolandopalermo.controller;

import com.rolandopalermo.domain.Employee;
import com.rolandopalermo.test.DummyDAO;
import com.rolandopalermo.util.ResponseList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

 * @author rolan
public class HomeController {

    @RequestMapping(value = {"/", "/home"}, method = RequestMethod.GET)
    public ModelAndView home() {
        ModelAndView model = new ModelAndView();
        return model;

    @RequestMapping(value = {"/get-all-employees"}, method = RequestMethod.POST)
    @CrossOrigin(origins = "*", allowCredentials = "true")
    public String getAllEmployees(HttpServletRequest request, HttpServletResponse response) {
        String json;
        try {
            ResponseList<Employee> lstInvoices = DummyDAO.getAllEmployees();
            json = lstInvoices.toString();
        } catch (Exception e) {
            json = "{"error" : true, "message": "" + e.getMessage() + "."}";
        return json;
$(document).ready(function () {
        method: "POST",
        url: 'get-all-employees',
        dataType: 'json',
        crossDomain: true,
        beforeSend: function (xhr) {
            //Set authentication headers
        success: function (data, textStatus, jqXHR) {
            if (data.error) {
            } else {
                var selector = $("#applications");
                data = $.parseJSON(selector.text());
                table = $("#employees").DataTable({
                    data: data,
                    scrollX: true,
                    scrollCollapse: true,
                    fixedColumns: true,
                    columns: [{
                            data: "id",
                            visible: false
                        }, {
                            data: "name"
                        }, {
                            data: "surname"
                        }, {
                            data: "age"
                        }, {
                            data: "address"
                        }, {
                            data: "status",
                            render: function (value) {
                                switch (value) {
                                    case "ACTIVE":
                                        return '<span class=active></span>';
                                    case "PENDING":
                                        return '<span class=pending></span>';
                                    case "INACTIVE":
                                        return '<span class=inactive></span>';
                                    case "DELETED":
                                        return '<span class=deleted></span>';
                                        return '<span class=active></span>';
        error: function (xhr) { // if error occured
            alert('No se pudo procesar la solicitud.');
        complete: function () {
        xhrFields: {
            withCredentials: true
    Document   : view
    Created on : Jan 20, 2017, 7:15:31 PM
    Author     : Rolando

<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8" %>
<%@taglib prefix="spring" uri=""%>
<%@taglib prefix="c" uri=""%>
<script type="text/javascript" src="<c:url value='/static/app/third-party/js/jquery-1.12.4.js' />"></script>
<script type="text/javascript" src="<c:url value='/static/app/third-party/datatables/js/jquery.dataTables.min.js' />"></script>
<script type="text/javascript" src="<c:url value='/static/app/third-party/datatables/js/dataTables.buttons.min.js' />"></script>
<script type="text/javascript" src="<c:url value='/static/app/js/home.js' />"></script>
<link href="<c:url value='/static/app/third-party/datatables/css/jquery.dataTables.min.css'/>" rel="stylesheet"/>
<link href="<c:url value='/static/app/third-party/datatables/css/buttons.dataTables.min.css'/>" rel="stylesheet"/>
<link href="<c:url value='/static/app/css/master.css'/>" rel="stylesheet"/>

<!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>How to use Jquery datatable in Spring MVC</title>
        <div id="applications" style="display: none"></div>
        <table id="employees" cellspacing="0" width="100%">
And your output should look like:

Download the full source code from Github and enjoy it!