1 minute read

검색 추가

<!-- 검색 form -->
<form action="/board/search" method="GET">
    <div>
        <input name="keyword" type="text" placeholder="검색어를 입력해주세요">
    </div>

    <button>검색하기</button>
</form>


검색 컨트롤러 추가

@GetMapping("/board/search")
public String search(@RequestParam(value="keyword") String keyword, Model model) {
    List<BoardDto> boardDtoList = boardService.searchPosts(keyword);
    
    model.addAttribute("boardList", boardDtoList);
    
    return "board/list.html";
}


검색 서비스 추가

@Transactional
public List<BoardDto> searchPosts(String keyword) {
    List<BoardEntity> boardEntities = boardRepository.findByTitleContaining(keyword);
    List<BoardDto> boardDtoList = new ArrayList<>();

    if (boardEntities.isEmpty()) return boardDtoList;

    for (BoardEntity boardEntity : boardEntities) {
        boardDtoList.add(this.convertEntityToDto(boardEntity));
    }

    return boardDtoList;
}

private BoardDto convertEntityToDto(BoardEntity boardEntity) {
    return BoardDto.builder()
            .id(boardEntity.getId())
            .title(boardEntity.getTitle())
            .content(boardEntity.getContent())
            .writer(boardEntity.getWriter())
            .createdDate(boardEntity.getCreatedDate())
            .build();
}


검색 리포지토리 추가

/*Containing =  Like 역할*/
public interface BoardRepository extends JpaRepository<BoardEntity, Long> {
    List<BoardEntity> findByTitleContaining(String keyword);
}


페이징 추가

<div>
    <span th:each="pageNum : ${pageList}" th:inline="text">
        <a th:href="@{'/?page=' + ${pageNum}}">[[${pageNum}]]</a>
    </span>
</div>


페이징 컨트롤러 추가

@GetMapping("/")
public String list(Model model, @RequestParam(value="page", defaultValue = "1") Integer pageNum) {
List<BoardDto> boardList = boardService.getBoardlist(pageNum);
Integer[] pageList = boardService.getPageList(pageNum);

model.addAttribute("boardList", boardList);
model.addAttribute("pageList", pageList);

return "board/list.html";
}


페이징 서비스 추가

    @Transactional
    public List<BoardDto> getBoardlist(Integer pageNum) {
        Page<BoardEntity> page = boardRepository.findAll(PageRequest.of(pageNum - 1, PAGE_POST_COUNT, Sort.by(Sort.Direction.ASC, "createdDate")));

        List<BoardEntity> boardEntities = page.getContent();
        List<BoardDto> boardDtoList = new ArrayList<>();

        for (BoardEntity boardEntity : boardEntities) {
            boardDtoList.add(this.convertEntityToDto(boardEntity));
        }

        return boardDtoList;
    }

    @Transactional
    public Long getBoardCount() {
        return boardRepository.count();
    }

    public Integer[] getPageList(Integer curPageNum) {
        Integer[] pageList = new Integer[BLOCK_PAGE_NUM_COUNT];

        // 총 게시글 갯수
        Double postsTotalCount = Double.valueOf(this.getBoardCount());

        // 총 게시글 기준으로 계산한 마지막 페이지 번호 계산 
        Integer totalLastPageNum = (int)(Math.ceil((postsTotalCount/PAGE_POST_COUNT)));

        // 현재 페이지를 기준으로 블럭의 마지막 페이지 번호 계산
        Integer blockLastPageNum = (totalLastPageNum > curPageNum + BLOCK_PAGE_NUM_COUNT)
                ? curPageNum + BLOCK_PAGE_NUM_COUNT
                : totalLastPageNum;

        // 페이지 시작 번호 조정
        curPageNum = (curPageNum <= 3) ? 1 : curPageNum - 2;

        // 페이지 번호 할당
        for (int val = curPageNum, idx = 0; val <= blockLastPageNum; val++, idx++) {
            pageList[idx] = val;
        }

        return pageList;
    }

카테고리:

업데이트:

댓글남기기