[Spring] 필터 만들어보기

19·2022년 7월 27일
0

Spring

목록 보기
11/29

원인

필터가 있었으면 좋겠다는 피드백이 있어서 적용해보았다.
조회수 순, 댓글 많은 순으로 게시글을 조회하는 필터를 만들어 보았는데, 잘 된 건지는 모르겠다ㅎㅎ..


적용

서버에서 필터 기능을 만드는 것은 어렵지 않았다.
단순히 게시글을 어떤 기준으로 조회할 지 repository나 service에서 가공해주고 클라이언트에게 반환해주면 됐기 때문이당

조회수 순 (인기순)

| PostRepository.java

public interface PostRepository extends JpaRepository<Post, Long> {
    List<Post> findAllByOrderByHitsDesc();
    ...
  • 조회수 기준 내림차순으로 게시글 목록을 가져온다.
    • 조회수가 큰 게시글부터 조회된다.

| PostService.java

// 조회수 순, 게시글 목록 조회 (모집 마감 포함)
public ResponseEntity<List<PostReadResponseDto>> readHitsPostList() {
    List<Post> hitsPosts = postRepository.findAllByOrderByHitsDesc();
    List<PostReadResponseDto> hitsPostList = new ArrayList<>();
    for (Post post : hitsPosts) {
        hitsPostList.add(PostReadResponseDto.builder()
                .status(StatusMessage.SUCCESS)
                .id(post.getId())
                .title(post.getTitle())
                .content(post.getContent())
                .meetingType(post.getMeetingType())
                .contact(post.getContact())
                .period(post.getPeriod())
                .recruitmentState(post.isRecruitmentState())
                .hits(post.getHits())
                .postDate(post.getCreateDate())
                .writer(post.getMember().getNickname())
                .build()
        );
    }
    return new ResponseEntity<>(hitsPostList, HttpStatus.valueOf(StatusCode.SUCCESS));
}
  • Repository에서 만든 메소드를 사용해 조회수 기준 내림차순으로 정렬된 게시글 목록을 가져오고 이를 반환해주면 끝!

| PostController.java

// 조회수순 게시글 목록 조회 (모집 마감 포함)
@GetMapping("/post/list/hits")
public ResponseEntity<List<PostReadResponseDto>> readHitsPostList() {
    return postService.readHitsPostList();
}
  • 해당 URL로 AJAX 요청이 오면 조회수 기준 내림차순으로 정렬된 게시글 목록을 획득할 수 있다!

'인기순'으로 드롭다운값을 변경하면, 조회수가 많은 게시글부터 조회된다



댓글 많은 순

댓글이 많이 작성된다는 건 그만큼 사람들이 관심을 가진다는 것이기에 댓글 많은 순으로 게시글을 정렬하는 필터도 추가해보았다.


| PostService.java

// 댓글 많은 순으로 게시글 목록 조회 (모집 마감 포함)
public ResponseEntity<List<PostReadResponseDto>> readCommentsPostList() {
    List<Post> posts = postRepository.findAll();
    
    // 댓글 많은 순으로 정렬
    getCommentsPosts(posts);

    List<PostReadResponseDto> commentsPostList = new ArrayList<>();
    for (Post post : posts) {
        commentsPostList.add(PostReadResponseDto.builder()
                .status(StatusMessage.SUCCESS)
                .id(post.getId())
                .title(post.getTitle())
                .content(post.getContent())
                .meetingType(post.getMeetingType())
                .contact(post.getContact())
                .period(post.getPeriod())
                .recruitmentState(post.isRecruitmentState())
                .hits(post.getHits())
                .postDate(post.getCreateDate())
                .writer(post.getMember().getNickname())
                .build()
        );
    }
    return new ResponseEntity<>(commentsPostList, HttpStatus.valueOf(StatusCode.SUCCESS));
}

// 댓글수 내림차순으로 게시글 정렬 (버블 정렬)
private List<Post> getCommentsPosts(List<Post> posts) {
    for (int i = 0; i< posts.size()-1; i++) {
        boolean swap = false;

        for (int j = 0; j< posts.size()-1-i; j++) {
            if(posts.get(j).getComments().size() < posts.get(j+1).getComments().size()) {
                Collections.swap(posts, j, j+1);
                swap = true;
            }
        }
        if (swap == false) {
            break;
        }
    }
    return posts;
}

댓글 수를 기준으로 게시글을 정렬하는 것은 어려웠다..ㅜ
어떻게 해야할 지 고민하던 중에, 예전에 버블 정렬을 배웠던 기억이 났고 이를 활용해보기로 했다.

  1. DB에서 게시글 목록을 가져온다.
  2. 댓글수 기준, 내림차순으로 정렬하는 메소드를 통해 정렬
    2-1. 버블 정렬을 활용해 댓글이 많은 순서대로 게시글을 정렬한다.
  3. 정렬된 게시글을 Dto 리스트에 담고 클라이언트에 반환

| PostController.java

// 댓글 많은 순 게시글 목록 조회 (모집 마감 포함)
@GetMapping("/post/list/comments")
public ResponseEntity<List<PostReadResponseDto>> readCommentsPostList() {
    return postService.readCommentsPostList();
}
  • 해당 URL로 AJAX 요청이 오면 댓글이 많은 순서대로 정렬된 게시글 목록을 획득할 수 있다!


사진에서 확인할 수는 없지만 댓글순으로 정렬되었다.
('테스트2'의 댓글은 3개이고, '테스트3'의 댓글은 1개이다.)


클라이언트

필터 구현 (클라이언트)

profile
하나씩 차근차근

0개의 댓글