Sunday, January 17, 2021

Spring MVC Pagination Example Using PagedListHolder

In this post we’ll see a Spring MVC pagination example using the PagedListHolder class.

Technologies used

Following is the list of tools used for the Spring MVC pagination example.

  1. Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  2. Java 10
  3. Tomcat server V 9.0.10
  4. Eclipse IDE

Spring MVC pagination using PagedListHolder

PagedListHolder is a simple state holder for handling lists of objects, separating them into pages. Page numbering starts with 0. PagedListHolder class has many methods thal help with pagination some of the methods which are used in the pagination example are as follows-

  • setSource(java.util.List<E> source)- Set the source list for this holder.
  • setPageSize(int pageSize)- Set the current page size.
  • setPage(int page)- Set the current page number. Page numbering starts with 0.
  • previousPage()- Switch to previous page.
  • nextPage()- Switch to next page.
  • isFirstPage()- Return if the current page is the first one.
  • isLastPage()- Return if the current page is the last one.
  • doSort(java.util.List<E> source, SortDefinition sort)- Sorts the given source list, according to the given sort definition.

Spring MVC Project structure using Maven

Spring MVC pagination example

In this Spring pagination example list of users is set as source to the PagedListHolder. Records in that list are then paginated using the methods of the PagedListHolder class. So, in the UI you’ll have Previous, Next and Number of pages as per records per page.

Spring MVC pagination example – Model bean

Model bean used in the example.

public class User {
 private String firstName;
 private String lastName;
 private String email;
 public User() {
  
 }
 public User(String firstName, String lastName, String email) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.email = email;
 }

 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
}

Spring MVC pagination example – Controller class

The controller class has one method which caters to both /showUser and /showUser/{page} URIs. The PathVariable which is {page} gets the value “prev”, “next” or page numbers (1,2,3..) and based on that value PageListHolder is set to previous page, next page or the passed page number.

@Controller
@RequestMapping(value = "/showUser")
public class UserController {
  @RequestMapping(value = {"", "/{page}"}, method = RequestMethod.GET)
  public ModelAndView showUser(@PathVariable(required=false, name="page") String page, HttpServletRequest request, HttpServletResponse response) {
    ModelAndView mv = new ModelAndView();
    PagedListHolder<User> userList;
    if(page == null) {
      userList = new PagedListHolder<User>();
      List<User> usersList = getListOfUsers();
      // Setting the source for PagedListHolder
      userList.setSource(usersList);
      userList.setPageSize(2);
      // Setting PagedListHolder instance to session
      request.getSession().setAttribute("userList", userList);
    }else if(page.equals("prev")) {
      // get the user list from session
      userList = (PagedListHolder<User>)request.getSession().getAttribute("userList");
      // switch to previous page
      userList.previousPage();
    }else if(page.equals("next")) {
      userList = (PagedListHolder<User>)request.getSession().getAttribute("userList");
      // switch to next page
      userList.nextPage();
    }else {
      int pageNum = Integer.parseInt(page);
      userList = (PagedListHolder<User>)request.getSession().getAttribute("userList");
      // set the current page number
      // page number starts from zero in PagedListHolder that's why subtracting 1
      userList.setPage(pageNum - 1);
    }
    
    mv.setViewName("user");
    return mv;
  }
    
  // Dummy method for adding List of Users
  private List<User> getListOfUsers() {
    List<User> users = new ArrayList<User>();
    users.add(new User("Jack", "Reacher", "abc@xyz.com"));    
    users.add(new User("Remington", "Steele", "rs@cbd.com"));
    users.add(new User("Laura", "Holt", "lh@cbd.com"));
    users.add(new User("Jonathan", "Raven", "jr@sn.com"));
    users.add(new User("Tom", "Hanson", "th@jd.com"));
    users.add(new User("Alexander", "Scott", "as@is.com"));
    users.add(new User("Jim", "Phelps", "jp@mi.com"));
    return users;
  }
}

When the path variable- page is null (i.e. /showUser URI) at that time List of users is created and stored to the PagedListHolder instance. That instance of PagedListHolder is set to the Session and used for other requests too, that way you don’t have to call the method to get the list of users every time.

Spring MVC pagination example – View

user.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC pagination tutorial</title>
</head>
<body>
<c:set value="${userList}" var="userPageList" />
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
<c:forEach items="${userPageList.pageList}" var="user">
<tr>
<td>${user.firstName}</td>
<td>${user.lastName}</td>
<td>${user.email}</td>    
</tr>
</c:forEach>
</table>
<br/>
<c:choose>
  <%-- Show Prev as link if not on first page --%>
  <c:when test="${userPageList.firstPage}">
    <span>Prev</span>
  </c:when>
  <c:otherwise>
    <c:url value="/showUser/prev" var="url" />                  
    <a href='<c:out value="${url}" />'>Prev</a>
  </c:otherwise>
</c:choose>
<c:forEach begin="1" end="${userPageList.pageCount}" step="1"  varStatus="tagStatus">
  <c:choose>
    <%-- In PagedListHolder page count starts from 0 --%>
    <c:when test="${(userPageList.page + 1) == tagStatus.index}">
      <span>${tagStatus.index}</span>
    </c:when>
    <c:otherwise>
      <c:url value="/showUser/${tagStatus.index}" var="url" />                  
      <a href='<c:out value="${url}" />'>${tagStatus.index}</a>
    </c:otherwise>
  </c:choose>
</c:forEach>
<c:choose>
  <%-- Show Next as link if not on last page --%>
  <c:when test="${userPageList.lastPage}">
    <span>Next</span>
  </c:when>
  <c:otherwise>
    <c:url value="/showUser/next" var="url" />                  
    <a href='<c:out value="${url}" />'>Next</a>
  </c:otherwise>
</c:choose>
</body>
</html>

Spring MVC Pagination example using Java config

Since JSTL is used here so you need to set the view class as JSTL view.

public class SpringMVCConfigInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

  @Override
  protected Class<?>[] getRootConfigClasses() {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  protected Class<?>[] getServletConfigClasses() {
    return new Class<?>[] {WebConfig.class};
  }

  @Override
  protected String[] getServletMappings() {
    return new String[] {"/"};
  }
}
@Configuration
@EnableWebMvc
@ComponentScan(basePackages="org.netjs.controller")
public class WebConfig implements WebMvcConfigurer {
 
 @Bean
 public ViewResolver viewResolver() {
  InternalResourceViewResolver resolver = new InternalResourceViewResolver();
  resolver.setViewClass(JstlView.class);
  resolver.setPrefix("/WEB-INF/jsp/");
  resolver.setSuffix(".jsp");
  return resolver;
 }
 /**
  * Configure a handler to delegate unhandled requests by forwarding to the
  * Servlet container's "default" servlet. A common use case for this is when
  * the {@link DispatcherServlet} is mapped to "/" thus overriding the
  * Servlet container's default handling of static resources.
  */
 public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
  configurer.enable();
 }
}

Deploying and running the application

Now is the time to package your web application as a war. Right click on project, select Maven build, in the opened window enter Goals as clean install and run it.

You can add Tomcat server to Eclipse IDE and run it from there itself, it is more convenient.

Right click on the added server and select “Add and Remove” you should see the application on the left hand side. You can select it and move it to right side so that it is configured to run on TomCat Server.

Start the server, once the Tomcat server is successfully started you can run your Spring Web MVC application.

To see all the records paginated as per the configuration.

http://localhost:8080/springmvc-config/showUser

Spring MVC pagination example

If you click next-

Spring MVC pagination example with PagedListHolder

If you click on page number-

Spring MVC pagination example

That's all for this topic Spring MVC Pagination Example Using PagedListHolder. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring MVC Configuring Multiple View Resolvers Example
  2. Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice
  3. Spring MVC Excel Generation Example
  4. Spring MVC JSON as Response Example
  5. Spring Batch Processing With List of Objects in batchUpdate() Method

You may also like-

  1. @Import Annotation in Spring JavaConfig
  2. Autowiring Using Annotations in Spring
  3. Spring Integration With Quartz Scheduler
  4. Spring Web Reactive Framework - Spring WebFlux Tutorial
  5. How to Sort ArrayList in Java
  6. AutoBoxing And UnBoxing in Java
  7. String charAt() And substring() Methods in Java
  8. How to Handle Missing And Under Replicated Blocks in HDFS

1 comment:

  1. i have large no of pages so how to hide middle pages.Does spring provide any support for it.

    ReplyDelete