[중 프로젝트] 스프링부트 카테고리별 페이징

Glen(OH TaekJoo)·2023년 6월 20일
0

Study

목록 보기
18/53
  • 같은 엔티티의 컬럼값에 따라 가져오는 값을 다르게 받는 메서드를 추가하여 카테고리별 페이징 .
  • 해당 카테고리를 클릭하면 해당 카테고리별 url이 새로 맵핑되도록 a태그에 url값 설정
  • 새로 받은 페이징, 객체값을 적용할 수 있도록 리스트 페이지 타임리프 수정

-동일한 방법으로 MarketList 페이지도 카테고리별 추가

컨트롤러

@GetMapping("/list")
public String list(Model model, @RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "kw", defaultValue = "") String kw) {
Page

paging = this.articleService.getList(page, kw);
List articles = this.articleService.getAll();
int articleCount = articles.size();
model.addAttribute("articles", articles);
model.addAttribute("articleCount", articleCount);
model.addAttribute("paging", paging);
model.addAttribute("kw", kw);
return "article_list";
}

@GetMapping(value = "/detail/{id}")
public String articleDetail(Model model, @PathVariable("id") Integer id) {
    Article article = this.articleService.getArticle(id);
    model.addAttribute("article", article);
    return "article_detail";
}

// 가격범위 카데고리 리스트 맵핑

@GetMapping(value = "/list/under/{id}")
public String list(Model model, @RequestParam(value = "page", defaultValue = "0") int page,
                   @RequestParam(value = "kw", defaultValue = "") String kw, @PathVariable("id") Integer price) {
    int min;
    int max;
    if (price == 15) {
        min = 0;
        max = 150000;
        Page<Article> paging = this.articleService.getPriceList(page, kw, min, max);
        List<Article> articles = this.articleService.getByPrice(min, max);
        // 받은 url값을 기준으로 미니멈, 맥시멈 값을 지정하여 서비스로 넘김 .
        int articleCount = articles.size();
        model.addAttribute("articles", articles);
        model.addAttribute("articleCount", articleCount);
        model.addAttribute("paging", paging);
        model.addAttribute("kw", kw);
    } else if (price == 30) {
        min = 150000;
        max = 300000;
        Page<Article> paging = this.articleService.getPriceList(page, kw, min, max);
        List<Article> articles = this.articleService.getByPrice(min, max);
        int articleCount = articles.size();
        model.addAttribute("articles", articles);
        model.addAttribute("articleCount", articleCount);
        model.addAttribute("paging", paging);
        model.addAttribute("kw", kw);
    } else if (price == 50) {
        min = 300000;
        max = 500000;
        Page<Article> paging = this.articleService.getPriceList(page, kw, min, max);
        List<Article> articles = this.articleService.getByPrice(min, max);
        int articleCount = articles.size();
        model.addAttribute("articles", articles);
        model.addAttribute("articleCount", articleCount);
        model.addAttribute("paging", paging);
        model.addAttribute("kw", kw);
    } else {
        min = 500000;
        max = 5000000;
        Page<Article> paging = this.articleService.getPriceList(page, kw, min, max);
        List<Article> articles = this.articleService.getByPrice(min, max);
        int articleCount = articles.size();
        model.addAttribute("articles", articles);
        model.addAttribute("articleCount", articleCount);
        model.addAttribute("paging", paging);
        model.addAttribute("kw", kw);
    }

    return "article_list";
}

// 시즌,타입  카데고리 리스트 맵핑 시즌=serson , 타입=type

@GetMapping("/list/{category}")
public String list(Model model, @RequestParam(value = "page", defaultValue = "0") int page,
                   @RequestParam(value = "kw", defaultValue = "") String kw, @PathVariable("category") String category) {
    if (category.equals("season_all")) {
        Page<Article> paging = this.articleService.getSeasonList(page, kw, "사계");
        List<Article> articles = this.articleService.getBySeason("사계");
        int articleCount = articles.size();
        model.addAttribute("articles", articles);
        model.addAttribute("articleCount", articleCount);
        model.addAttribute("paging", paging);
        model.addAttribute("kw", kw);
    } else if (category.equals("season_summer")) {
        Page<Article> paging = this.articleService.getSeasonList(page, kw, "하계");
        List<Article> articles = this.articleService.getBySeason("하계");
        int articleCount = articles.size();
        model.addAttribute("articles", articles);
        model.addAttribute("articleCount", articleCount);
        model.addAttribute("paging", paging);
        model.addAttribute("kw", kw);

    } else if (category.equals("season_winter")) {
        Page<Article> paging = this.articleService.getSeasonList(page, kw, "동계");
        List<Article> articles = this.articleService.getBySeason("동계");
        int articleCount = articles.size();
        model.addAttribute("articles", articles);
        model.addAttribute("articleCount", articleCount);
        model.addAttribute("paging", paging);
        model.addAttribute("kw", kw);
    } else if (category.equals("type_tent")) {
        Page<Article> paging = this.articleService.getTypeList(page, kw, "텐트/타프");
        List<Article> articles = this.articleService.getByType("텐트/타프");
        int articleCount = articles.size();
        model.addAttribute("articles", articles);
        model.addAttribute("articleCount", articleCount);
        model.addAttribute("paging", paging);
        model.addAttribute("kw", kw);
    } else if (category.equals("type_table")) {
        Page<Article> paging = this.articleService.getTypeList(page, kw, "테이블");
        List<Article> articles = this.articleService.getByType("테이블");
        int articleCount = articles.size();
        model.addAttribute("articles", articles);
        model.addAttribute("articleCount", articleCount);
        model.addAttribute("paging", paging);
        model.addAttribute("kw", kw);
    } else if (category.equals("type_chair")) {
        Page<Article> paging = this.articleService.getTypeList(page, kw, "의자");
        List<Article> articles = this.articleService.getByType("의자");
        int articleCount = articles.size();
        model.addAttribute("articles", articles);
        model.addAttribute("articleCount", articleCount);
        model.addAttribute("paging", paging);
        model.addAttribute("kw", kw);
    } else if (category.equals("type_lanturn")) {
        Page<Article> paging = this.articleService.getTypeList(page, kw, "랜턴");
        List<Article> articles = this.articleService.getByType("랜턴");
        int articleCount = articles.size();
        model.addAttribute("articles", articles);
        model.addAttribute("articleCount", articleCount);
        model.addAttribute("paging", paging);
        model.addAttribute("kw", kw);
    } else if (category.equals("type_cook")) {
        Page<Article> paging = this.articleService.getTypeList(page, kw, "조리도구");
        List<Article> articles = this.articleService.getByType("조리도구");
        int articleCount = articles.size();
        model.addAttribute("articles", articles);
        model.addAttribute("articleCount", articleCount);
        model.addAttribute("paging", paging);
        model.addAttribute("kw", kw);
    } else if (category.equals("type_etc")) {
        Page<Article> paging = this.articleService.getTypeList(page, kw, "기타");
        List<Article> articles = this.articleService.getByType("기타");
        int articleCount = articles.size();
        model.addAttribute("articles", articles);
        model.addAttribute("articleCount", articleCount);
        model.addAttribute("paging", paging);
        model.addAttribute("kw", kw);
    }


    return "article_list";
}

;

서비스

public Page

getList(int page, String kw) {
List<Sort.Order> sorts = new ArrayList<>();
sorts.add(Sort.Order.desc("createDate"));
Pageable pageable = PageRequest.of(page, 9, Sort.by(sorts));
Specification spec = search(kw);
return this.articleRepository.findAll(spec, pageable);
}

public Page<Article> getSeasonList(int page, String kw, String season) {
    List<Sort.Order> sorts = new ArrayList<>();
    sorts.add(Sort.Order.desc("createDate"));
    Pageable pageable = PageRequest.of(page, 9, Sort.by(sorts));
    Specification<Article> spec = searchSeason(season);
    return this.articleRepository.findAll(spec, pageable);
}

public Specification<Article> searchSeason(String sea) {
    return (root, query, criteriaBuilder) -> {
        List<Predicate> predicates = new ArrayList<>();

        // Season 컬럼을 기준으로 검색 조건 생성
        if (sea != null) {
            Path<String> seasonPath = root.get("season");
            Predicate seasonPredicate = criteriaBuilder.equal(seasonPath, sea);
            predicates.add(seasonPredicate);
        }

        // 다른 조건들을 추가하고 싶다면 여기에 추가

        // 검색 조건들을 조합하여 최종 검색 조건 생성
        return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
    };
}

public Page<Article> getTypeList(int page, String kw, String type) {
    List<Sort.Order> sorts = new ArrayList<>();
    sorts.add(Sort.Order.desc("createDate"));
    Pageable pageable = PageRequest.of(page, 9, Sort.by(sorts));
    Specification<Article> spec = searchType(type);
    return this.articleRepository.findAll(spec, pageable);
}

public Specification<Article> searchType(String sea) {
    return (root, query, criteriaBuilder) -> {
        List<Predicate> predicates = new ArrayList<>();

        // Season 컬럼을 기준으로 검색 조건 생성
        if (sea != null) {
            Path<String> typePath = root.get("type");
            Predicate typePredicate = criteriaBuilder.equal(typePath, sea);
            predicates.add(typePredicate);
        }

        // 다른 조건들을 추가하고 싶다면 여기에 추가

        // 검색 조건들을 조합하여 최종 검색 조건 생성
        return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
    };
}

public Page<Article> getPriceList(int page, String kw, int min, int max) {
    List<Sort.Order> sorts = new ArrayList<>();
    sorts.add(Sort.Order.desc("createDate"));
    Pageable pageable = PageRequest.of(page, 9, Sort.by(sorts));
    Specification<Article> spec = (root, query, builder) -> {
        return builder.between(root.get("price"), min, max);
    };
    // 비트윈으로 미니멈, 맥시멈값 지정후 spec변수에 담고 해당변수값의 아티클만 파인드올로 불러옴  //
    return this.articleRepository.findAll(spec, pageable);
}


public Article getArticle(Integer id) {
    Optional<Article> article = this.articleRepository.findById(id);
    if (article.isPresent()) {
        return article.get();
    } else {
        throw new DataNotFoundException("article not found");
    }
}

public void create(String subject, String content, Integer price, Integer starScore, String season, String type, SiteUser user) {
    Article q = new Article();
    q.setSubject(subject);
    q.setContent(content);
    q.setCreateDate(LocalDateTime.now());
    q.setAuthor(user);
    q.setPrice(price);
    q.setStarScore(starScore);
    q.setSeason(season);
    q.setType(type);
    this.articleRepository.save(q);
}


public List<Article> getMainCategory(String mainCategory) {
    return this.articleRepository.findByMainCategory(mainCategory);
}


public List<Article> getAll() {

    return this.articleRepository.findAll();
}

public List<Article> getByType(String type) {

    return this.articleRepository.findByType(type);
}

public List<Article> getBySeason(String season) {

    return this.articleRepository.findBySeason(season);
}

public void modify(Article article, String subject, String content, String type, String season, int price, int starscore) {
    article.setSubject(subject);
    article.setContent(content);
    article.setPrice(price);
    article.setSeason(season);
    article.setType(type);
    article.setStarScore(starscore);
    article.setModifyDate(LocalDateTime.now());
    this.articleRepository.save(article);
}

public void delete(Article article) {
    this.articleRepository.delete(article);
}

public void vote(Article article, SiteUser siteUser) {
    article.getVoter().add(siteUser);
    this.articleRepository.save(article);
}

public List<Article> getByPrice(int min, int max) {

    return this.articleRepository.findByPriceBetween(min, max);
    // 비트윈을 사용하면 인트값의 범위를 지정하여 불러올 수 있다. (프라이스가 int값으로 지정되어있음 )
}

html

ListlPage
        <div class="signIn" sec:authorize="isAnonymous()" th:href="@{/user/login}">
            <a href="http://localhost:8080/user/login">
                <button type="button" class="signIn_button">
                    <img src="https://i.postimg.cc/dQGcFnFG/login.png" class="signIn_img"/>
                    <span>로그인</span>
                </button>
            </a>
        </div>

        <div class="signUp" sec:authorize="isAuthenticated()" th:href="@{/user/logout}">
            <a href="http://localhost:8080/mypage">
                <button type="button" class="signUp_button">
                    <img src="https://i.postimg.cc/wMXCkx2w/mypage.png" class="signUp_img"/>
                    <span>마이페이지</span>
                </button>
            </a>
        </div>
        <div class="signUp" sec:authorize="isAnonymous()" th:href="@{/user/login}">
            <a href="http://localhost:8080/user/signup_menual">
                <button type="button" class="signUp_button">
                    <img src="https://i.postimg.cc/vHzRgBcB/signup.png" class="signUp_img"/>
                    <span>회원가입</span>
                </button>
            </a>
        </div>
    </div>
</nav>
  • 답글수    추천수
                        <div class="review_board_text_box_tag">
                            <span>#</span>
                            <span th:text="${article.type}"></span>
                            <span>,</span>
                            <span>#</span>
                            <span th:text="${article.season}"></span>
                        </div>
                    </nav>
                </li>
            </ul>
        </div>
        <div class="pagination-1">
            <div class="pagination">
                <ul class="page-list">
                    <li th:classappend="${!paging.hasPrevious} ? 'disabled'">
                        <a class="page-link"
                           th:href="${paging.hasPrevious} ? @{|?page=${paging.number+1}|} : @{|?page=0|}">
                            <span>이전</span>
                        </a>
                    </li>
                    <li th:each="page: ${#numbers.sequence(0, paging.totalPages)}"
                        th:if="${page >= paging.number-3 and page <= paging.number+3}"
                        th:classappend="${page == paging.number} ? 'active'"
                        class="page-item">
                        <a th:text="${page}" class="page-link" th:href="@{|?page=${page}|}"></a>
                    </li>
                    <li th:classappend="${!paging.hasNext} ? 'disabled'">
                        <a class="page-link"
                           th:href="${paging.hasNext} ? @{|?page=${paging.number+1}|} : @{|?page=${paging.totalPages}|}">
                            <span>다음</span>
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
profile
병아리 개발자 의 우당탕탕 성장기

0개의 댓글