728x90
* 페이징 코드는 내가 원하는 값으로 나오기 위해 작성한 것으로
블로그는 참고만 해서 정확하게 맞는 코드인지는 모름
RegistryController
@RequiredArgsConstructor
@RestController
public class RegistryController {
private final RegistryService registryService;
// 게시글 등록
@PostMapping("/registry") //@RequestParam이 여러개 있다. -> @ModelAttribute
public Registry setUpload(@ModelAttribute RegistryDto registryDto) throws IOException {
return registryService.setUpload(registryDto);
}
// 작성 글 페이징
@GetMapping("/space/{curPage}")
public PagingResult readBoard(@PathVariable Integer curPage) {
return registryService.getBoards(curPage);
}
// 게시글 상세 보기
@GetMapping("/registry")
public Registry getIdxRegistry(@RequestParam Long idx) {
return registryService.getIdxRegistry(idx);
}
}
RegistryService
@RequiredArgsConstructor
@Service
public class RegistryService {
private final RegistryRepository registryRepository;
// private static final int BLOCK_PAGE_NUM_COUNT = 5; // 블럭에 존재하는 페이지 번호 수
private static final int PAGE_POST_COUNT = 9; // 한 페이지에 존재하는 게시글 수
private int displayPageNum = 5; // 화면 하단에 보여지는 페이지 버튼의 수
private int startPage; // 화면에 보여지는 페이징 5개 중 시작 페이지 번호
private int endPage; // 화면에 보여지는 페이징 5개 중 마지막 페이지 번호, 끝 페이지 번호
private boolean prev; // 이전 버튼 생성 여부
private boolean next; // 다음 버튼 생성 여부
private int nowPage; // 현재 페이지
// 게시글 등록
@Transactional
public Registry setUpload(RegistryDto registryDto) throws IOException {
Registry registry = new Registry(registryDto);
registryRepository.save(registry);
return registry;
}
// 작성 글 페이징
public PagingResult getBoards(int curPage) {
Pageable pageable = PageRequest.of(curPage-1, PAGE_POST_COUNT);
// 찾을 페이지, 한 페이지의 size
Page<Registry> boards = registryRepository.findAllByOrderByCreatedAtDesc(pageable);
// 생성 날짜 순으로 보여주기
List<Registry> boardList = boards.getContent();
// 조회된 데이터
nowPage = (boards.getNumber()+1);
// client와 server 인덱스 값이 1 차이
startPage = ( ((int) Math.ceil(nowPage/ (double) displayPageNum )) -1) *5 +1;
endPage = startPage+4;
prev = startPage == 1 ? false : true; // 이전 버튼 생성 여부
next = endPage < boards.getTotalPages()? true : false;
if(endPage >= boards.getTotalPages()) {
endPage = boards.getTotalPages();
next = false;
}
return new PagingResult(boardList, boards.getTotalPages(), startPage, endPage, prev, next);
// 조회된 모든 데이터, 전체 페이지 수, ..
}
// 게시글 상세 보기
public Registry getIdxRegistry(Long idx) {
Registry getIdxRegistry = registryRepository.findById(idx).orElseThrow(
() -> new NullPointerException("해당 게시글 없음")
);
return getIdxRegistry;
}
}
추가 설명
더보기
페이징 처리
Pageable pageable = PageRequest.of(curPage-1, PAGE_POST_COUNT);
프론트에서 전체 사용자 정보를 조회하는 요청이 들어오면 Repository에서 findAll() 메소드를 통해
해당 데이터를 front에게 응답을 내려주면 되지만 이러한 데이터를 한 페이지에 보여주기에는 무리가 있다.
이런 경우 Pageable 객체를 통해서 간단하게 구현할 수 있다.
*Pageable의 구현체 : PageRequest
삼항연산자
prev = startPage == 1 ? false : true; // 이전 버튼 생성 여부
startPage == 1 이 조건문 // 참일 때 fasle, 거짓일 떄 true가 나온다.
참고 : [ [Java] 삼항연산자 사용법 & 예제 ]
Pageable pageable = PageRequest.of(curPage-1, PAGE_POST_COUNT); // 찾을 페이지, 한 페이지의 size
(index)
client → server : 1부터 시작
server → client : 0부터 시작
ex) client(5) = server(4)
Pageable의 page는 배열의 index처럼 0부터 시작하고, 사용자에게 보여지는 페이지는 1부터 시작한다.
if(endPage >= boards.getTotalPages()) {
endPage = boards.getTotalPages();
next = false;
}
ex)
5 >= 6 // → false
= = = = = = = = = =
4 >= 3 // → true
3=3
RegistryDto
@Setter
@Getter
public class RegistryDto {
private String nickname;
private String title;
private String main;
}
RegistryRepository
public interface RegistryRepository extends JpaRepository<Registry, Long> {
// 생성 날짜 순으로 보여주기(desc : 내림차순)
Page<Registry> findAllByOrderByCreatedAtDesc(Pageable pageable);
}
Registry
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@Entity
@ToString
public class Registry extends Timestamped {
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
@Column(name = "RegistryId")
private Long idx;
@Column(nullable = false)
private String nickname;
@Column(nullable = false)
private String title;
@Column(nullable = false)
private String main;
public Registry(RegistryDto registryDto) {
this.title = registryDto.getTitle();
this.main = registryDto.getMain();
this.nickname = registryDto.getNickname();
}
}
728x90
'Project' 카테고리의 다른 글
paging test 코드 보기(검증x) (0) | 2022.05.27 |
---|---|
Registry 코드 정리 - front (+ 페이징) (0) | 2022.05.25 |
웹 소켓 코드 정리 (0) | 2022.03.30 |
1, 2차 프로젝트 gif 정리 (0) | 2022.03.29 |
3차 프로젝트 gif (0) | 2022.03.28 |