Spring MVC 为什么列表在客户端不分页,而是显示所有结果?

fnvucqvd  于 2023-01-13  发布在  Spring
关注(0)|答案(1)|浏览(146)

我遇到了一个非常奇怪的bug。基本上,在控制器中,当我联系"/categories/page/{pageNum} "端点并将关键字作为参数传递时,客户端返回分页列表。相反,当我联系客户端中的"/categories"端点时,列表没有分页,但返回所有结果。下面我将向您展示所有代码执行中固有的类。

@GetMapping("/categories")
    @PreAuthorize("hasAnyAuthority('Admin', 'Editor')")
    public String listFirstPage(@Param("sortDir") String sortDir, Model model) {
        if(sortDir == null)
            sortDir = "asc";
        return listByPage(1, "name", null, model);
    }
    
    @GetMapping("/categories/page/{pageNum}")
    public String listByPage(@PathVariable("pageNum")int pageNum,
            @Param("sortDir") String sortDir,
            @Param("keyword") String keyword,
            Model model) {
        if (sortDir == null || sortDir.isEmpty()) {
            sortDir = "asc";
        }
        
        CategoryPageInfo pageInfo = new CategoryPageInfo();
        List<Category> listByPage = service.listByPage(pageInfo, pageNum, sortDir, model, keyword);
        
         long startCount = (pageNum - 1) * CategoryService.ROOT_CATEGORY_PER_PAGE + 1;
         long endCount = startCount + CategoryService.ROOT_CATEGORY_PER_PAGE -1;
         if(endCount > pageInfo.getTotalElement())
             endCount = pageInfo.getTotalElement();
        
        String reverseSortDir = sortDir.equals("asc") ? "desc" : "asc";
        
        model.addAttribute("totalPages", pageInfo.getTotalPages());
        model.addAttribute("totalElements", pageInfo.getTotalElement());
        model.addAttribute("currentPage", pageNum);
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("sortField", "name");
        model.addAttribute("sortDir", sortDir);
        model.addAttribute("keyword", keyword);
        model.addAttribute("categories", listByPage);
        model.addAttribute("startCount", startCount);
        model.addAttribute("endCount", endCount);
        model.addAttribute("reverseSortDir", reverseSortDir);
        return "categories/categories.html";
    }
package com.shopme.admin.category;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import com.shopme.admin.FileUploadUtil;
import com.shopme.common.entity.Category;

import jakarta.transaction.Transactional;

@Service
@Transactional
public class CategoryService {
    public static final int ROOT_CATEGORY_PER_PAGE = 4;

    @Autowired
    private CategoryRepository repo;

    public List<Category> listByPage(CategoryPageInfo pageInfo, int pageNum, String sortDir, Model model,
            String keyword) {
        Sort sort = Sort.by("name");

        if (sortDir.equals("asc")) {
            sort = sort.ascending();
        } else if (sortDir.equals("desc")) {
            sort = sort.descending();
        }

        Pageable pageable = PageRequest.of(pageNum - 1, ROOT_CATEGORY_PER_PAGE, sort);

        Page<Category> categoriesPage = null;

        if (keyword != null && !keyword.isEmpty()) {
            categoriesPage = repo.search(keyword, pageable);
        } else {
            categoriesPage = repo.findRootCategoriesPage(pageable);
        }

        List<Category> rootCategories = categoriesPage.getContent();

        pageInfo.setTotalElement(categoriesPage.getTotalElements());
        pageInfo.setTotalPages(categoriesPage.getTotalPages());

        if (keyword != null && !keyword.isEmpty()) {
            List<Category> searchResult = categoriesPage.getContent();
            for(Category category : searchResult) {
                category.setHasChildren(category.getChildren().size() > 0);
            }
            
            return searchResult;
            
        } else {
            return listHierarchicalCategories(rootCategories, sortDir);
        }
        
        
    }

    private List<Category> listHierarchicalCategories(List<Category> rootCategories, String sortDir) {
        List<Category> listHierarchicalCategories = new ArrayList<>();

        for (Category rootCategory : rootCategories) {
            listHierarchicalCategories.add(Category.copyFull(rootCategory));

            Set<Category> children = sortSubCategory(rootCategory.getChildren(), sortDir);

            for (Category subCategory : children) {
                String name = "--" + subCategory.getName();
                listHierarchicalCategories.add(Category.copyFull(subCategory, name));

                listSubHierarchicalCategories(listHierarchicalCategories, subCategory, 1, sortDir);
            }
        }

        return listHierarchicalCategories;
    }

    private void listSubHierarchicalCategories(List<Category> listHierarchicalCategories, Category parent, int subLevel,
            String sortDir) {
        Set<Category> children = sortSubCategory(parent.getChildren(), sortDir);
        int newSubLevel = subLevel + 1;

        for (Category subCategory : children) {
            StringBuilder name = new StringBuilder();
            for (int i = 0; i < newSubLevel; i++) {
                name.append("--");
            }
            name.append(subCategory.getName());

            listHierarchicalCategories.add(Category.copyFull(subCategory, name.toString()));

            listSubHierarchicalCategories(listHierarchicalCategories, subCategory, newSubLevel, sortDir);
        }

    }

在我看来,我认为我需要限制搜索结果也在所有子类别,我添加

bn31dyow

bn31dyow1#

由于在使用“/categories”获取记录时未传递pageNumber,因此它将打印所有记录,您必须将默认值设置为属性,以便在未传递值时仍受该值的限制,请使用以下代码:-

@PathVariable(value="pageNum",defaultValue="1",reuired="false")int 
pageNum)

相关问题