Home » Enterprise Java » spring » MVC » Spring MVC Pagination Example

About Yatin

The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

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

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
Spring MVC Pagination - Model View Controller (MVC) Overview

Fig. 1: Model View Controller (MVC) Overview

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!

Spring MVC Pagination - Application Project Structure

Fig. 2: Application Project Structure

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.

Spring MVC Pagination - Create a Maven Project

Fig. 3: Create a 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.

Spring MVC Pagination - Project Details

Fig. 4: Project Details

Select the Maven Web App archetype from the list of options and click next.

Spring MVC Pagination - Archetype Selection

Fig. 5: Archetype Selection

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.

Spring MVC Pagination - Archetype Parameters

Fig. 6: Archetype Parameters

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:


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

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.


-- Create database springmvcpagination

CREATE DATABASE springmvcpagination;

-- Table structure for table employee_tbl

CREATE TABLE Employee_tbl (

-- Dumping data for table employee_tbl

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

Spring MVC Pagination - Database & Table Creation

Fig. 7: Database & Table Creation

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:


<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">
	<name>SpringMvcPagination Maven Webapp</name>
		<!-- Servlet API Dependency -->
		<!-- Spring Framework Dependencies -->
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<!-- https://mvnrepository.com/artifact/jstl/jstl -->

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:


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"



	<!-- Database configuration file. -->


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:


<?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"
        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 />

		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />

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:


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<!-- Database information. -->
	<bean id="ds"
		<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 id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="ds"></property>

	<bean id="edao" class="com.spring.mvc.dao.EmpDaoImpl">
		<property name="template" ref="jdbcTemplate"></property>

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:


package com.spring.mvc.model;

import org.springframework.stereotype.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;

	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:


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;

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();

				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:


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;

public class EmpServImpl implements EmpServ {

	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:


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;

public class EmpCtrl {

	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:


<%@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">
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
		<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">
			    	<c:forEach var="emp" items="${list}">
			  <!-- 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>

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.

Spring MVC Pagination - Deploy Application on Tomcat

Fig. 8: How to Deploy Application on Tomcat

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.


Server name (localhost) and port (8082) may vary as per your tomcat configuration.

Spring MVC Pagination - Output

Fig. 9: Output

Users can click on the navigation links to display the next set of records as shown in Fig. 10.

Spring MVC Pagination - Pagination

Fig. 10: Pagination

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
(No Ratings Yet)
1 Comment Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area


Leave a Reply

1 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
S Ravi Kumar Recent comment authors
newest oldest most voted
Notify of
S Ravi Kumar
S Ravi Kumar

How do you know that total no. of pages are only 3?