페이징 기능이 구현된 상태에서 검색 기능을 구현되게 만들기
페이지가 바뀌어도 검색 텍스트를 유지할 수 있다.
@Query(value = "SELECT * FROM board WHERE title LIKE %:searchText% or content LIKE %:searchText%", nativeQuery = true)
Page<Board> findByTitleOrContent(String searchText, Pageable page);
public Page<Board> 게시글목록보기(Pageable page, String searchText) {
return boardRepository.findByTitleOrContent(searchText, page);
}
// 게시글 목록보기
@GetMapping("/board")
public String home(Model model,
@PageableDefault(page = 0, size = 3, sort = "id", direction = Sort.Direction.DESC) Pageable page,
@RequestParam(required = false, defaultValue = "") String searchText) {
Page<Board> boardsEntity = boardRepository.findByTitleOrContent(searchText, page);
int startPage = Math.max(1, boardsEntity.getPageable().getPageNumber() - 4);
int endPage = Math.min(boardsEntity.getTotalPages(), boardsEntity.getPageable().getPageNumber() + 4);
int nowPage = boardsEntity.getPageable().getPageNumber() + 1;
model.addAttribute("startPage", startPage);
model.addAttribute("endPage", endPage);
model.addAttribute("nowPage", nowPage);
model.addAttribute("boardsEntity", boardService.게시글목록보기(page, searchText));
return "board/list";
}
// 검색창
<form class="row g-3 d-fex justify-content-end" >
<div class="col-auto">
<input type="text" class="form-control" name="searchText" value="${param.searchText}" >
</div>
<div class="col-auto">
<button type="submit" class="btn btn-primary mb-3">검색</button>
</div>
</form>
// ...게시글 리스트 생략...
// 페이징
<ul class="pagination d-flex justify-content-center">
<c:choose>
<c:when test="${boardsEntity.first}">
<li class="page-item disabled"><a class="page-link"
href="/board?page=${boardsEntity.number - 1}&searchText=${param.searchText}">Prev</a></li>
</c:when>
<c:otherwise>
<li class="page-item"><a class="page-link"
href="/board?page=${boardsEntity.number - 1}&searchText=${param.searchText}">Prev</a></li>
</c:otherwise>
</c:choose>
<c:forEach begin="${startPage}" end="${endPage}" var="idx">
<c:choose>
<c:when test="${idx eq nowPage}">
<li class="page-item disabled"><a
class="page-link page-active" href="/board?page=${idx-1}&searchText=${param.searchText}">${idx}</a></li>
</c:when>
<c:otherwise>
<li class="page-item"><a class="page-link"
href="/board?page=${idx-1}&searchText=${param.searchText}">${idx}</a></li>
</c:otherwise>
</c:choose>
</c:forEach>
<c:choose>
<c:when test="${boardsEntity.last}">
<li class="page-item disabled"><a class="page-link"
href="/board?page=${param.page + 1}&searchText=${param.searchText}">Next</a></li>
</c:when>
<c:otherwise>
<li class="page-item"><a class="page-link"
href="/board?page=${param.page + 1}&searchText=${param.searchText}">Next</a></li>
</c:otherwise>
</c:choose>
</ul>