Java 如何在 Spring MVC 3 中实现分页

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2245035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:11:34  来源:igfitidea点击:

How to implement pagination in Spring MVC 3

javaspringspring-mvcservletspagination

提问by Nachiket

Is there any out-of-the-box, easy to implement, standard pagination component/tag-lib or code-sample available for pagination in Spring MVC?

是否有任何开箱即用、易于实现的标准分页组件/标签库或代码示例可用于 Spring MVC 中的分页?

采纳答案by Pascal Thivent

Have a look at PagedListHolderand other classes from org.springframework.beans.support.

看看PagedListHolder来自 org.springframework.beans.support.

See the JPetstore in the samples for some examples, e.g. in SearchProductsController.java:

有关示例,请参阅示例中的 JPetstore,例如SearchProductsController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String keyword = request.getParameter("keyword");
    if (keyword != null) {
        if (!StringUtils.hasLength(keyword)) {
            return new ModelAndView("Error", "message", "Please enter a keyword to search for, then press the search button.");
        }
        PagedListHolder productList = new PagedListHolder(this.petStore.searchProductList(keyword.toLowerCase()));
        productList.setPageSize(4);
        request.getSession().setAttribute("SearchProductsController_productList", productList);
        return new ModelAndView("SearchProducts", "productList", productList);
    }
    else {
        String page = request.getParameter("page");
        PagedListHolder productList = (PagedListHolder) request.getSession().getAttribute("SearchProductsController_productList");
        if (productList == null) {
            return new ModelAndView("Error", "message", "Your session has timed out. Please start over again.");
        }
        if ("next".equals(page)) {
            productList.nextPage();
        }
        else if ("previous".equals(page)) {
            productList.previousPage();
        }
        return new ModelAndView("SearchProducts", "productList", productList);
    }
}

回答by Daff

I was looking for a way to do that, too, but didn't find any standard component or taglib. I think mainly because paging can become very specific since you need to retrieve your data with paging from the database already (if you are using Hibernate you can easily do that using the Criteria API). I came up with something like this:

我也在寻找一种方法来做到这一点,但没有找到任何标准组件或标签库。我认为主要是因为分页可以变得非常具体,因为您需要已经从数据库中通过分页检索数据(如果您使用的是 Hibernate,您可以使用 Criteria API 轻松做到这一点)。我想出了这样的事情:

public class Pager
{
    private int page;
    private int results;
    private String sortOrder;
    private String sortColumn;

    // Getters and setters
}

@Controller
public class StuffController
{
    @Autowired SomeEntityService someEntityService;

    @RequestMapping("/test.html", method = Method.GET)
    public void getStuffPaged(@RequestParam("id") String id, Pager pager, ModelMap mm)
    {
        mm.addAttribute("entities", someEntityService.get(id, pager));
    }
}

If you now perform a request to http://domain/app/test.html?id=10&page=1&results=30&sortOrder=ascyou will get the pager Object in your request.

如果您现在执行一个请求,http://domain/app/test.html?id=10&page=1&results=30&sortOrder=asc您将在您的请求中获得寻呼机对象。

回答by BalusC

No one comes to mind and Googlealso doesn't reveal any specific components for that (although it gives pretty much concrete examples and hints). But in theory just a bunch of buttons and one (or two) request parameters are more than sufficient. Then let the SQL/DB do its work. I've posted an answer to similar question in JSP/Servlet/DAO context before here.

没有人想到,谷歌也没有透露任何具体的组件(尽管它提供了非常具体的例子和提示)。但理论上只要一堆按钮和一个(或两个)请求参数就足够了。然后让 SQL/DB 完成它的工作。我在这里之前在 JSP/Servlet/DAO 上下文中发布了类似问题的答案。

It basically boils down to pass firstrow(index of first row to be displayed in a page) around as request parameter and having two buttons/links in the pagination form which in/decrements the firstrowwith rowcount(amount of rows displayed at once in a page) in combination with a SQL query which returns a subset of the results with help of under each LIMIT, OFFSETclauses, or subselects, or specific functions, depending on the DB in question. See the aforelinked answer for detailed code examples and SQL queries.

它基本上归结为传递firstrow(要在页面中显示的第一行的索引)作为请求参数,并在分页表单中有两个按钮/链接,它们在/减少firstrowwith rowcount(在页面中一次显示的行数)结合 SQL 查询,该查询在 under each LIMITOFFSET子句或子选择或特定函数的帮助下返回结果的子集,具体取决于所讨论的数据库。有关详细的代码示例和 SQL 查询,请参阅上述答案。

回答by S?awomir Borowiec

Have you ever heard about the Spring Data JPA project? There is a nice flexible solution using the Pagable interface. I've found it to be the simplest way to achieve clean, boilerplate-free pagination. Check out more at the Spring Data JPA homepage.

您听说过 Spring Data JPA 项目吗?使用 Pagable 接口有一个很好的灵活解决方案。我发现它是实现干净、无样板分页的最简单方法。在Spring Data JPA 主页上查看更多信息

回答by S?awomir Borowiec

Here's a link to the Spring Data JPA reference docs, where they have a very clean approach to web pagination.

这是 Spring Data JPA 参考文档的链接,其中有一种非常干净的网页分页方法。

回答by Jose Luis Martin

I published an open source java library focused on pagination with spring framework some time ago.

前段时间我发布了一个开源的java库,专注于使用spring框架进行分页。

Although it has not been very successful perhaps someone may be interested in trying it.

虽然它不是很成功,但也许有人有兴趣尝试一下。

There are examples for using it with

有使用它的例子

The online examples are somewhat obsolete, better download the jdal-samples file from sourceforge.

在线示例有些过时,最好从sourceforge下载 jdal-samples 文件。