Spring MVC Pagination Example
Pagination is a mechanism to display a large number of records in different parts. In this tutorial, we will show how to implement the pagination functionality in the spring mvc framework.
1. Introduction
- Spring is an open-source framework created to address the complexity of an enterprise application development
- One of the chief advantages of the Spring framework is its layered architecture, which allows a developer to be selective about which of its components they can use while providing a cohesive framework for
J2EE
application development - Spring framework provides support and integration to various technologies for e.g.:
- Support for Transaction Management
- Support for interaction with the different databases
- Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
- Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
- Support for
REST
style web-services
Table Of Contents
1.1 Spring Mvc Framework
Model-View-Controller (Mvc) is a well-known design pattern for designing the GUI based applications. It mainly decouples the business logic from UI by separating the roles of Model, View, and Controller in an application. This pattern divides the application into three components to separate the internal representation of the information from the way it is being presented to the user. The three components are:
- Model (M): Model’s responsibility is to manage the application’s data, business logic, and business rules. It is a
POJO
class which encapsulates the application data given by the controller - View (V): A view is an output representation of the information, such as displaying information or reports to the user either as a text-form or as charts. Views are usually the
JSP
templates written with Java Standard Tag Library (JSTL
) - Controller (C): Controller’s responsibility is to invoke the Models to perform the business logic and then update the view based on the model’s output. In the spring framework, the controller part is played by the Dispatcher Servlet
Now, open up the Eclipse IDE and let us see how to implement the pagination in the spring mvc framework.
2. Spring MVC Pagination Example
Here is a systematic guide for implementing this tutorial in the Spring Mvc framework.
2.1 Tools used
We are using Eclipse Kepler SR2, MySQL, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project structure
Firstly, let us review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
2.3 Project creation
This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select the project location. By default, ‘Use default workspace location’ will be selected. Just click on the next button to proceed.
Select the Maven Web App archetype from the list of options and click next.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.spring.mvc</groupId> <artifactId>SpringMvcPagination</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> </project>
We can start adding the dependencies that developers want like Servlet API, Spring Mvc, and MySQL. Let us start building the application!
3. Application building
Below are the steps involved in developing this application.
3.1 Database and Table creation
The following MySQL script creates a database called springmvcpagination
with a table: Employee_tbl
. Open MySQL terminal or workbench terminal and execute the SQL script.
Script
-- -- Create database springmvcpagination -- CREATE DATABASE springmvcpagination; -- -- Table structure for table employee_tbl -- CREATE TABLE Employee_tbl ( EMPLOYEE_ID int(11) NOT NULL AUTO_INCREMENT, EMPLOYEE_FULLNAME varchar(100) NOT NULL, EMPLOYEE_DESIGNATION varchar(100) NOT NULL, EMPLOYEE_SALARY decimal(10,2) NOT NULL, PRIMARY KEY (EMPLOYEE_ID) ); -- -- Dumping data for table employee_tbl -- INSERT INTO Employee_tbl (EMPLOYEE_ID, EMPLOYEE_FULLNAME, EMPLOYEE_DESIGNATION, EMPLOYEE_SALARY) VALUES (1, 'Daniel', 'Technical Lead', '1300000.00'), (2, 'Charlotte', 'Technical Lead', '1100000.00'), (3, 'Rakesh', 'Software Developer', '550000.00'), (4, 'Jane', 'Senior Software Developer', '970000.00'), (5, 'Smith', 'UI Developer', '1000000.00'), (6, 'Bob', 'Associate HR', '80000.00'), (7, 'Rahul', 'Senior Software Developer', '90000.00'), (8, 'Rakesh', 'UI Developer', '25000.00'), (9, 'Udit', 'Junior Developer', '35000.00'), (10, 'Jai', 'Technical Lead', '45000.00'), (11, 'Nikhil', 'UI Developer', '55000.00'), (12, 'Somesh', 'Senior Software Developer', '65000.00'), (13, 'Rajesh', 'Manager', '75000.00'), (14, 'Ankit', 'UI Developer', '85000.00'), (15, 'Ratan', 'Technical Lead', '95000.00'); -- -- Selecting data from table employee_tbl -- SELECT * FROM Employee_tbl;
If everything goes well, the table will be shown in the MySQL Workbench.
3.2 Maven dependencies
Here, we specify the dependencies for the Spring Mvc and MySQL. Maven will automatically resolve the rest dependencies such as Spring Beans, Spring Core etc. The updated file will have the following code:
pom.xml
<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.spring.mvc</groupId> <artifactId>SpringMvcPagination</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringMvcPagination Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- Servlet API Dependency --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> <!-- Spring Framework Dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.8.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.12</version> </dependency> <!-- https://mvnrepository.com/artifact/jstl/jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> </build> </project>
3.3 Configuration files
Let us write all the configuration files involved in this application.
3.3.1 Web deployment descriptor
The web.xml
file declares one servlet (i.e. Dispatcher Servlet) to receive all kind of the requests. Dispatcher servlet here acts as a front controller. Add the following code to it:
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>SpringMvcPagination</display-name> <servlet> <servlet-name>mvcpaginationdispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>mvcpaginationdispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- Database configuration file. --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/database.cfg.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
3.3.2 Spring configuration file
To configure the spring framework, developers need to implement a bean configuration file i.e. mvcpaginationdispatcher-servlet.xml
which provide an interface between the basic Java class and the outside world. Put this XML file in the SpringMvcPagination/src/main/webapp/WEB-INF
folder and add the following code to it:
mvcpaginationdispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.spring.mvc" /> <context:component-scan base-package="com.spring.mvc.dao" /> <context:component-scan base-package="com.spring.mvc.model" /> <context:component-scan base-package="com.spring.mvc.service" /> <context:annotation-config /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
3.3.3 Database configuration file
To configure the database settings, we need to implement a bean configuration file i.e. database.cfg.xml
which provide the database connection details. Put this XML file in the SpringMvcPagination/src/main/webapp/WEB-INF
folder and add the following code to it:
database.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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.xsd"> <!-- Database information. --> <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/springmvcpagination" /> <property name="username" value="root" /> <property name="password" value="" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="ds"></property> </bean> <bean id="edao" class="com.spring.mvc.dao.EmpDaoImpl"> <property name="template" ref="jdbcTemplate"></property> </bean> </beans>
3.4 Java classes
Let us write the Java classes involved in this application.
3.4.1 Model class
The pojo class defines the employee schema. Add the following code to it:
Emp.java
package com.spring.mvc.model; import org.springframework.stereotype.Component; @Component public class Emp { private int id; private String name; private String designation; private float salary; public Emp() { } public Emp(int id, String name, String designation, float salary) { this.id = id; this.name = name; this.designation = designation; this.salary = salary; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public float getSalary() { return salary; } public void setSalary(float salary) { this.salary = salary; } @Override public String toString() { return "Employee [Id=" + id + ", Name=" + name + ", Designation=" + designation + ", Salary=" + salary + "]"; } }
3.4.2 DAO class
The data-access-object class fetches the employee records from the database. Add the following code to it:
EmpDaoImpl.java
package com.spring.mvc.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import com.spring.mvc.model.Emp; @Repository public class EmpDaoImpl implements EmpDao { private JdbcTemplate template; public JdbcTemplate getTemplate() { return template; } public void setTemplate(JdbcTemplate template) { this.template = template; } public List<Emp> getEmployeesByPage(int pageid, int total) { String sql= "SELECT * FROM Employee_tbl LIMIT "+(pageid-1)+","+total; return getTemplate().query(sql, new RowMapper<Emp>() { public Emp mapRow(ResultSet rs, int rowNum) throws SQLException { Emp emp = new Emp(); emp.setId(rs.getInt("EMPLOYEE_ID")); emp.setName(rs.getString("EMPLOYEE_FULLNAME")); emp.setDesignation(rs.getString("EMPLOYEE_DESIGNATION")); emp.setSalary(rs.getInt("EMPLOYEE_SALARY")); return emp; } }); } }
3.4.3 Service class
The service class will call the data-access-object method to fetch the employee data from the database. Add the following code to it:
EmpServImpl.java
package com.spring.mvc.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.spring.mvc.dao.EmpDao; import com.spring.mvc.model.Emp; @Service public class EmpServImpl implements EmpServ { @Autowired private EmpDao edao; public List<Emp> getEmployeesByPage(int pageid, int total) { return edao.getEmployeesByPage(pageid, total); } }
3.4.4 Controller class
The controller class is responsible for handling the incoming request which is configured by the @RequestMapping
annotation. Add the following code to it:
EmpCtrl.java
package com.spring.mvc; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.spring.mvc.model.Emp; import com.spring.mvc.service.EmpServ; @Controller public class EmpCtrl { @Autowired EmpServ eserv; @RequestMapping(value= "/init/{page_id}", method= RequestMethod.GET) public ModelAndView paginate(@PathVariable int page_id) { int total = 5; if(page_id == 1) { // do nothing! } else { page_id= (page_id-1)*total+1; } List<Emp> list = eserv.getEmployeesByPage(page_id, total); return new ModelAndView("welcome", "list", list); } }
3.5 JSP view
Spring mvc supports many types of views for different presentation technologies. These include – JSP
, HTML
, XML
etc. So let us write a simple result view in SpringMvcPagination/src/main/webapp/WEB-INF/views/
folder.
3.5.1 Output page
This is the output page of this tutorial and displays the output. Add the following code to it:
welcome.jsp
<%@page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@page isELIgnored="false"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Success</title> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <link rel="stylesheet" href="https://examples.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.1.3/css/bootstrap.min.css"> </head> <body> <div class="container"> <h2 align="center" class="text-primary">Spring Mvc Pagination Example</h2><hr /> <div> </div> <!-- Table to show the data fetched from the db. --> <table class="table" align="center"> <thead> <tr> <th>Id</th><th>Name</th><th>Designation</th><th>Salary</th> </tr> </thead> <tbody> <c:forEach var="emp" items="${list}"> <tr> <td>${emp.id}</td><td>${emp.name}</td><td>${emp.designation}</td><td>${emp.salary}</td> </tr> </c:forEach> </tbody> </table> <!-- Pagination links in spring mvc. --> <ul class="pagination pagination-sm"> <li class="page-item"><a class="page-link" href="/SpringMvcPagination/init/1">1</a></li> <li class="page-item"><a class="page-link" href="/SpringMvcPagination/init/2">2</a></li> <li class="page-item"><a class="page-link" href="/SpringMvcPagination/init/3">3</a></li> </ul> </div> </body> </html>
4. Run the application
As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server
.
Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.
5. Project demo
Open your favorite browser and hit the following URL to display the output page.
http://localhost:8082/SpringMvcPagination/
Server name (localhost) and port (8082) may vary as per your tomcat configuration.
Users can click on the navigation links to display the next set of records as shown in Fig. 10.
That’s all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!
6. Conclusion
In this section, developers learned how to implement the pagination functionality in the spring mvc framework. Developers can download the sample application as an Eclipse project in the Downloads section.
7. Download the Eclipse project
This was an example of Spring MVC Pagination.
You can download the full source code of this example here: SpringMvcPagination
How do you know that total no. of pages are only 3?
you can get number of rows in your table and divite it by ammount displayed on page