首页 > 解决方案 > how to implement pagination front-end in spring boot web application using jsp

问题描述

I have read many pagination examples and almost all of them are as Rest Services I did not find any example which is implemented as web page front-end. So till now, I have learned how to implement pagination at the back-end. I have proper methods in Controller, Service, Repository and I'm getting the resulted values from the database(MySQL).
My repository extends the JpaRepository and I'm implementing the pagination with pageable. Below are the method in my Controller, Service, Repository.

In Repository class

Page<SlUrl> findAllByOrderByCreationDateDesc(Pageable pageable);

In Service class (subtractPageByOne is because index start from 0 but the url parameter will start from 1)

public Page<SlUrl> getUrlsByPage(int pageNumber, int numberOfElementsPerPage) {

        return urlRepository.findAllByOrderByCreationDateDesc(PageRequest.of(subtractPageByOne(pageNumber), numberOfElementsPerPage));
    }

    private int subtractPageByOne(int page) {
        return (page < 1) ? 0 : page - 1;
    }

And in Controller class

@GetMapping("/urls")
    public ModelAndView openPageableUrls(ModelAndView mv, @RequestParam(defaultValue = "0") int page) {
        System.out.println("Inside /urls");
        Page<SlUrl> urls = slUrlService.getUrlsByPage(page, 5);
        List<SlUrl> urlList = urls.getContent();
        System.out.println("Url count = " + urls.getSize()
                + " Number = " + urls.getNumber() + "");

        mv.setViewName("userlinks");

        for (int i = 0; i < urlList.size(); i++) {
            System.out.println("\nURLs Details:"
                    + "\nid = " + urlList.get(i).getId()
                    + "\nid = " + urlList.get(i).getDestinationUrlLink()
                    + "\nid = " + urlList.get(i).getShortUrlLink()
                    + "\nid = " + urlList.get(i).getUser().getUsername());
        }

        return mv;
    }

You can see that I have a for loop to show the detail of SlUrl it's working fine. Now my question is what is the best way to show the above details on the front-end (JSP page). One way I think of is passing this urlList and use the for-each loop to show the data. But this data is just for example purpose what if I have to implement something like blog or to show version history.

So how to best represent the data at the front-end. A code example would be very helpful.

标签: javaspringspring-bootjsppagination

解决方案


为可能来到这篇文章的其他用户回答我自己的问题。
我找到了实现分页的GitHub 存储库,但它使用的是thymeleaf模板而不是 JSP 页面。因此,从那个存储库中,我为 JSP 页面构建了分页。

这是提供有关页面的所有信息的 Pager util 类

package packageNameHere;


import org.springframework.data.domain.Page;

/**
 * @author Inzimam Tariq
 */
public class Pager {

    private final Page<SlUrl> urls;

    public Pager(Page<SlUrl> urls) {
        this.urls = urls;
    }

    public int getPageIndex() {
        return urls.getNumber() + 1;
    }

    public int getPageSize() {
        return urls.getSize();
    }

    public boolean hasNext() {
        return urls.hasNext();
    }

    public boolean hasPrevious() {
        return urls.hasPrevious();
    }

    public int getTotalPages() {
        return urls.getTotalPages();
    }

    public long getTotalElements() {
        return urls.getTotalElements();
    }

    public Page<SlUrl> getSlUrls() {
        return urls;
    }

    public boolean indexOutOfBounds() {
        return getPageIndex() < 0 || getPageIndex() > getTotalElements();
    }

}

现在在控制器中,我将页面和寻呼机信息传递给 ModelAndView。整个方法看起来像这样

@GetMapping("/urls")
    public ModelAndView openPageableUrls(ModelAndView mv, HttpServletRequest request,
            @RequestParam(defaultValue = "0") int page) {
        System.out.println("Inside /urls");
        Page<SlUrl> urls = slUrlService.getUrlsByPage(page, 5);
        List<SlUrl> urlList = urls.getContent();
        System.out.println("Url count = " + urls.getSize()
                + " Number = " + urls.getNumber() + " Elements = " + urls.getNumberOfElements());
        Pager pager = new Pager(urls);

        mv.addObject("baseUrl", AppUtils.getBaseUrl(request));
        mv.addObject("pager", pager);
        urls.getTotalPages();
        mv.addObject("page", urls);
        mv.setViewName("pagination");

        for (int i = 0; i < urlList.size(); i++) {
            System.out.println("\nURLs Details:"
                    + "\nid = " + urlList.get(i).getId()
                    + "\nid = " + urlList.get(i).getDestinationUrlLink()
                    + "\nid = " + urlList.get(i).getShortUrlLink()
                    + "\nid = " + urlList.get(i).getUser().getUsername());
        }

        return mv;
    }

这是我的 pagination.jsp 页面,我在其中循环数据(在本例中为 URL)

<div class="container-fluid d-flex flex-column align-items-center justify-content-center"><br>
     <h1 class="display-4 d-md-display-4"><b>Title_Here</b></h1>
     <p>This is a long test text for demo paragraph.</p>

     <table class="table table-responsive table-striped table-hover table-bordered" style='vertical-align:middle'>
         <thead class="thead-dark">
             <tr>
                <th>Id</th>
                <th>Destination Url</th>
                <th>Short URL</th>
                <th>Actions</th>
             </tr>
         </thead>
         <tbody>
            <c:forEach var="links" items="${page.content}">
                <tr>
                <td>${links.getId()}</td>
                <td>${links.getDestinationUrlLink()}</td>
                <td>${links.getShortUrlLink()}</td>
                <td id="copyTd_${links.getId()}" hidden="">
                    <input type="text" id="${links.getId()}" value="${baseUrl}/${links.getShortUrlLink()}">
                </td>
                <td><button type="submit" id="copy_${links.getId()}" 
                           class="btn btn-success btn-block" 
                                                        onclick="copyShortLink(${links.getId()})"  data-toggle="tooltip" data-placement="top" title="Click to copy shortlink!">
                      Copy
                    </button>

                </td>
              </tr>
            </c:forEach>
          </tbody>
   </table>                   

   <div class="d-flex flex-row align-items-center">
      <c:if test="${pager.hasPrevious()}">
           <button type="submit" class="btn btn-primary btn-md" style="margin: 2px"
                   onclick="location.href = 'urls?page=1'">&laquo; first</button>
           <button type="submit" class="btn btn-primary btn-md" style="margin: 2px"
                    onclick="location.href = 'urls?page=${pager.getPageIndex() - 1}'">previous</button>
      </c:if>

      <c:if test="${pager.getTotalPages() != 1}">
            <label style="margin: 2px 8px 2px 8px">
                   Page ${pager.getPageIndex()} of  ${pager.getTotalPages()}
            </label>
      </c:if>

      <c:if test="${pager.hasNext()}">
            <button type="submit" class="btn btn-primary btn-md" style="margin: 2px"
                   onclick="location.href = 'urls?page=${pager.getPageIndex() + 1}'">next</button>
            <button type="submit" class="btn btn-primary btn-md" style="margin: 2px"
                   onclick="location.href = 'urls?page=${pager.getTotalPages()}'">last &raquo;</button>                                    
      </c:if>
    </div>

</div>

推荐阅读