스프링 부트에서 게시글 페이지를 임의로 넣었을 때, 마지막 페이지가 보이게 하기

LeeYulhee·2023년 9월 19일
0

👉 URL의 파라미터로 페이지를 임의로 넣었을 때 오류 발생


  • URL 파라미터 page= 값을 임의로 총 페이지보다 큰 값을 넣을 경우 발생
  • 클릭할 수 있는 페이지 수가 파라미터 기준으로 +- 값이기 때문에 오류 발생
  • 정상적으로 접근할 때는 오류 미발생



👉 원하는 구현 방향


  • 구현되어 있는 페이지보다 더 큰 값이 임의로 들어왔을 때 각 사이트 별로 구현한 방식은 달랐음
  • 내가 원한 방향은 마지막 페이지가 보여 지는 것이었음
    • 정상적인 접근은 아니지만 오류 페이지가 보일 정도의 문제는 아니라고 생각



👉 코드 수정


@GetMapping("/list")
@PreAuthorize("isAuthenticated()")
public String showList(Model model, @AuthenticationPrincipal SecurityUser user,
                       @RequestParam(defaultValue = "0") int page,
                       @RequestParam(defaultValue = "10") int size,
                       @RequestParam(defaultValue = "createDate") String sortCode,
                       @RequestParam(defaultValue = "DESC") String direction) {

    Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.fromString(direction), sortCode));

    Long currentUserId = user.getId();
    User currentUser = userService.findByIdElseThrow(currentUserId);

    Page<Notification> notifications = notificationService.findByInvitedUser(currentUser, pageable);

	// 추가한 부분
	// 제일 작은 page를 0으로 구현한 상태라 총 페이지 수의 - 1로 if문 작성
    if(page != 0 && page > notifications.getTotalPages() - 1) {
        page = notifications.getTotalPages() - 1;
        pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.fromString(direction), sortCode));
        notifications = notificationService.findByInvitedUser(currentUser, pageable);
    }

    notificationService.markAsRead(currentUser, pageable);

    model.addAttribute("notifications", notifications);
    model.addAttribute("currentPage", page);

    return "notification/list";
}
  • @RequestParam으로 매개변수를 받는데, page가 만약 0이 아니고 notifications의 총 페이지수 - 1 보다 크면 변수와 객체의 값을 바꾸어 대입
    • 현재 구현되어 있는 상태는 제일 작은 page가 0이라 총 페이지 수의 - 1로 검색
      • ⇒ 만약 시작 페이지가 1부터라면 - 1은 안 해도 됨
    • page에는 notifications의 총 페이지수 - 1을 대입(= 마지막 페이지)
    • pageable 객체에는 새로운 page 값을 넣어 대입
    • notifications에도 바뀐 pageable을 같이 넘겨준 값으로 대입



👉 적용된 결과 및 결론


  • URL 파라미터로 page를 임의로 총 페이지보다 큰 값을 넣었을 때, 파라미터의 변화는 없지만 화면은 목록의 마지막 페이지를 보여줌
  • 성능이 좋은 방향은 아닌 것 같지만 해당 방법이 스스로 떠올린 방법 중 오류 없이 구현하기 쉬웠음
    • 처음에는 redirect로 구현했었으나 Controller마다 구현된 로직이나 Service를 통해 검증하는 과정 등이 달라서 오류가 발생하는 경우가 많았음
    • notificationService.findByInvitedUser() 메서드를 두 번 호출하는 것은 불필요한 데이터베이스 액세스를 초래할 수 있으므로 추후에 수정하면 좋을 것 같음
profile
공부 중인 신입 백엔드 개발자입니다

0개의 댓글