Spring Boot + JQuery + DataTables
--
This tutorial will show you how easy is integrate Spring and DataTables.
Tech stack:
- Spring Boot(1.4.2)
- Maven (3.3.9)
- Eclipse (Neon, 4.6.0)
- Java 8
- Packaging (JAR)
- JPA
- Spring RESTful
- Spring MVC
- H2
- Thymeleaf
- DataTables
Project Creation
First we will use a very useful Spring initializer in order to create our maven project with the dependencies listed above.
- Go to → https://start.spring.io/
- Leave everything as it is and select the following dependencies: Web, JPA, H2 and Thymeleaf.
Click on Generate Project button and it will download a zip file (demo.zip) with our maven project.
Import Project into Eclipse
- Unzip the zip file.
- Import into Eclipse as “Existing Maven Project”
- Choose the root directory of the project generated (where the pom.xml file is located) and click on Finish.
It will display the next project structure.
In order to execute Thymeleaf in “LEGACYHTML5” mode, we need to add an extra dependency in our pom.xml file → nekohtml.
Also we need to add the following properties in the applicaiton.properties file (please refer this file below or in the github repository).
- spring.thymeleaf.mode=LEGACYHTML5
- spring.thymeleaf.cache=false
pom.xml file
application.properties file
Model Creation
Now let´s create our model class Employee(Entity class).
Data Layer (JPA Repositories)
EmployeeRepository
Service Layer
Now let´s create our user service layer(interface and implementation). We will inject the EmployeeRepository into our service implementation.
Interface
Implementation
MVC Controller
By default Spring Boot defines the view resolver in the next way.
- Prefix → resources/templates
- Suffix → html
Note: if you want to implement a custom view resolver you can do it using the application.properties file or the a java configuration file.
RESTful Controller
View (index.html)
CDN Dependencies:
- Bootstrap
- jQuery
- DataTables
datatable.js
Basically this java script file defines the datasource of the DataTable.
sAjaxSource executes the RESTful request defined in the EmployeeRestController file, it returns the employees stored in the database with a JSON format.
You can verify this RESTful call using your browser with the next url → http://localhost:8080/employees
Database Initialization
In order to populate our database we will execute a sql script with the inserts into employee table.
Out-of-the-box Spring Boot will execute automatically the file data.sql located in the project resources folder.
data.sql
Launch the application
- Run as Java Application the DemoApplication.java file.
- Open → http://localhost:8080/
Output
There are a lot of things that you can do with the DataTables: ordering, searching, rendering, event handlers, localization, etc.
Please refer the official documentation for further information.
Github repository
That´s all guys, if you have any question or feedback don’t hesitate to write your thoughts in the responses section.