Pagination is a commonly used function in Java Web projects. Yesterday, simple paging operations and search paging were implemented in Spring MVC. Let’s record it here. The framework used is (MyBatis+SpringMVC+Spring).
First we need a paginated tool class:
1. Pagination
import java.io.Serializable; /** * Pagination*/ public class Page implements Serializable { private static final long serialVersionUID = -3198048449643774660L; private int pageNow = 1; // Current page number private int pageSize = 4; // Number of records displayed on each page private int totalCount; // Total number of records private int totalPageCount; // Total number of pages @SuppressWarnings("unused") private int startPos; // Start position, start from 0 @SuppressWarnings("unused") private boolean hasFirst;// Is there a home page @SuppressWarnings("unused") private boolean hasPre;// Is there a previous page @SuppressWarnings("unused") private boolean hasNext;// Is there a next page @SuppressWarnings("unused") private boolean hasLast;// Is there a last page/** * Pass the total number of records and the current page through the constructor* @param totalCount * @param pageNow */ public Page(int totalCount, int pageNow) { this.totalCount = totalCount; this.pageNow = pageNow; } /** * Get the total number of pages, total number of pages = total records/total number of pages* @return */ public int getTotalPageCount() { totalPageCount = getTotalCount() / getPageSize(); return (totalCount % pageSize == 0) ? totalPageCount : totalPageCount + 1; } public void setTotalPageCount(int totalPageCount) { this.totalPageCount = totalPageCount; } public int getPageNow() { return pageNow; } public void setPageNow(int pageNow) { this.pageNow = pageNow; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } /** * Get the initial position of the selection record* @return */ public int getStartPos() { return (pageNow - 1) * pageSize; } public void setStartPos(int startPos) { this.startPos = startPos; } /** * Is it the first page* @return */ public boolean isHasFirst() { return (pageNow == 1) ? false : true; } public void setHasFirst(boolean hasFirst) { this.hasFirst = hasFirst; } /** * Is there a homepage* @return */ public boolean isHasPre() { // If there is a home page, there is the previous page, because there is a home page, it is not the first page. return isHasFirst() ? true : false; } public void setHasPre(boolean hasPre) { this.hasPre = hasPre; } /** * Is there a next page* @return */ public boolean isHasNext() { // If there is a last page, there is the next page, because there is a last page, it is not the last page. return isHasLast() ? true : false; } public void setHasNext(boolean hasNext) { this.hasNext = hasNext; } /** * Is there a last page* @return */ public boolean isHasLast() { // If it is not the last page, there will be a last page return (pageNow == getTotalCount()) ? false : true; } public void setHasLast(boolean hasLast) { this.hasLast = hasLast; } }With this tool class, first write the SQL statement in the XxxxMapper.xml configuration file of MyBatis, as follows:
<!-- Pagination SQL statement--> <select id="selectProductsByPage" resultMap="return value type"> select * from table name WHERE user_id = #{userId,jdbcType=INTEGER} limit #{startPos},#{pageSize} </select> <!-- Get the total number of records--> <select id="getProductsCount" resultType="long"> SELECT COUNT(*) FROM table name WHERE user_id = #{userId,jdbcType=INTEGER} </select>Here we can see that the two <select>s need to pass in 3 and 1 parameter respectively. At this time, write an interface in the corresponding DAO file IXxxxDao to write the corresponding method. The method name is the same as the id attribute value in mapper.xml:
/** * Pass multiple parameters using annotation method, user product pagination, query by logging in user ID* @param page * @param userId * @return startPos},#{pageSize} */ public List<Products> selectProductsByPage(@Param(value="startPos") Integer startPos,@Param(value="pageSize") Integer pageSize,@Param(value="userId") Integer userId); /** * Get product quantity information and query by logging in user ID* @param userId * @return */ public long getProductsCount(@Param(value="userId") Integer userId);After the interface definition is completed, you need to write the corresponding business interface and implementation method, define such a method in the interface, and then override it in the implementation class:
/** * Page display product* @param request * @param model * @param loginUserId */ void showProductsByPage(HttpServletRequest request,Model model,int loginUserId);
The next method to implement the class is to call the DAO layer and accept the parameters passed by the Controller to perform business logic processing. Request is used to obtain the parameters passed by the front-end, and model is used to return the processing results to the JSP page.
@Override public void showProductsByPage(HttpServletRequest request, Model model,int loginUserId) { String pageNow = request.getParameter("pageNow"); Page page = null; List<ProductWithBLOBs> products = new ArrayList<ProductWithBLOBs>(); int totalCount = (int) productDao.getProductsCount(loginUserId); if (pageNow != null) { page = new Page(totalCount, Integer.parseInt(pageNow)); allProducts = this.productDao.selectProductsByPage(page.getStartPos(), page.getPageSize(), loginUserId); } else { page = new Page(totalCount, 1); allProducts = this.productDao.selectProductsByPage(page.getStartPos(), page.getPageSize(), loginUserId); } model.addAttribute("products", products); model.addAttribute("page", page); }Next is the writing of the controller. When the user needs to jump to the page of this real product, he needs to go through the corresponding method in the controller. This processing process is to call the business layer method to complete, and then return the result to the JSP dynamic display. The server generates the page and pass it to the client (browser) for reality. This is an MVC process.
/** * Initialize the "My Products" list JSP page, with paging function* * @param request * @param model * @return */ @RequestMapping(value = "map path", method = RequestMethod.GET) public String showMyProduct(HttpServletRequest request, Model model) { // Get loginUser in SESSION User loginUser = (User) request.getSession().getAttribute("loginUser"); // Determine whether SESSION is invalid if (loginUser == null || "".equals(loginUser)) { return "redirect:/"; } int loginUserId = loginUser.getUserId(); //The productService here is an object of the injected IProductService interface this.productService.showProductsByPage(request, model, loginUserId); return "JSP path to jump to"; }I won't write the acceptance part of the JSP page. Everyone is the same, that is, they combine JSTL and EL to write it. (I also made a judgment when looping out. If the accepted parameters are empty, then there is no product for the output. Only when the accepted parameters are not empty will the output be looped out. Use <<c:when test="${}"> combined with <c:otherwise>), only the relevant code for the pagination is given here:
<!-- Paging function start --> <div align="center"> <font size="2">Total${page.totalPageCount} page</font> <font size="2">Page${page.pageNow}</font> <a href="myProductPage?pageNow=1" rel="external nofollow" rel="external nofollow" >Home</a> <c:choose> <c:when test="${page.pageNow - 1 > 0}"> <a href="myProductPage?pageNow=${page.pageNow - 1}" rel="external nofollow" >Previous page</a> </c:when> <c:when test="${page.pageNow - 1 <= 0}"> <a href="myProductPage?pageNow=1" rel="external nofollow" rel="external nofollow" >Previous page</a> </c:when> </c:choose> <c:choose> <c:when test="${page.totalPageCount==0}"> <a href="myProductPage?pageNow=${page.pageNow}" rel="external nofollow" rel="external nofollow" >Next page</a> </c:when> <c:when test="${page.pageNow + 1 < page.totalPageCount}"> <a href="myProductPage?pageNow=${page.pageNow + 1}" rel="external nofollow" >Next page</a> </c:when> <c:when test="${page.pageNow + 1 >= page.totalPageCount}"> <a href="myProductPage?pageNow=${page.totalPageCount}" rel="external nofollow" rel="external nofollow" >Next page</a> </c:when> </c:choose> <c:choose> <c:when test="${page.totalPageCount==0}"> <a href="myProductPage?pageNow=${page.pageNow}" rel="external nofollow" rel="external nofollow" >Last page</a> </c:when> <c:otherwise> <a href="myProductPage?pageNow=${page.totalPageCount}" rel="external nofollow" rel="external nofollow" >Last page</a> </c:otherwise> </c:choose> </div> <!-- Pagination Function End -->2. Query paging
Regarding query paging, the process is roughly the same, except that the third parameter (the above is loginUserId) needs to accept the user input parameters. In this way, we need to accept the user input parameter in the controller (the <input> in the page is passed in GET method), and then add it to SESSION to complete the query paging (here, due to the hyperlink in "Next Page", different JSP pages are used to handle paging and search paging. The method completed in a JSP page has not been found yet, and duplicate code appears. The duplicate code here is the code that outputs the content. You can take it out separately and load it with a <include> tag to the required JSP page, so that the code can be avoided):
Here is the code for the controller as a reference:
/** * Query the product by product name* @param request * @param model * @return */ @RequestMapping(value = "map address", method = RequestMethod.GET) public String searchForProducts(HttpServletRequest request, Model model) { HttpSession session = request.getSession(); String param = request.getParameter("param"); String condition = (String) session.getAttribute("condition"); //First determine whether the condition in SESSION is empty if (condition == null) { condition = new String(); session.setAttribute("condition", condition); //If the condition in Session is empty, then determine whether the passed parameter is empty. If it is empty, jump to the search result page if (param == null || "".equals(param)) { return "private/space/ProductSearchResult"; } } //If SESSION is not empty and the incoming search condition param is not empty, then assign param to condition if (param != null && !("".equals(param))) { condition = param; session.setAttribute("condition", condition); } //Use the condition attribute value in the session as the query condition this.productService.showSearchedProductsByPage(request, model, condition); return "jumped page"; }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.