검색 기능 1,2편
by 볼빵빵오춘기Repostitory
@Repository
public interface BoardRepository extends JpaRepository<Board,Integer> {
Page<Board> findByTitleContaining(String searchKeyword, Pageable pageable);
}
Service
public Page<Board> boardSearchList(String searchKeyword, Pageable pageable) {
return boardRepositoy.findByTitleContaining(searchKeyword, pageable);
}
Controller
@GetMapping("/board/list")
public String boardList(Model model, @PageableDefault(page = 0, size = 2,sort = "id",direction = Sort.Direction.DESC) Pageable pageable, String searchKeyword){
Page<Board> list = null;
if(searchKeyword == null) {
list = boardService.boardList(pageable);
}else {
list = boardService.boardSearchList(searchKeyword, pageable);
}
int nowPage = list.getPageable().getPageNumber() + 1;
int startPage = Math.max(nowPage - 4, 1);
int endPage = Math.min(nowPage + 5, list.getTotalPages());
model.addAttribute("list", list);
model.addAttribute("nowPage", nowPage);
model.addAttribute("startPage", startPage);
model.addAttribute("endPage", endPage);
return "boardList";
}
boardList.html
- 페이징 부분에 search도 같이 넘어가도록 수정한다.
- name이 searchKeyword 인 input이 들어간 form을 하나 추가한다.
<th:block th:each="page : ${#numbers.sequence(startPage, endPage)}">
<a th:if="${page != nowPage}" th:href="@{/board/list(page = ${page - 1}, searchKeyword = ${param.searchKeyword})}" th:text="${page}"></a>
<strong th:if="${page == nowPage}" th:text="${page}" style="color : red"></strong>
</th:block>
<form th:action="@{/board/list}" method="get">
<input type="text" name="searchKeyword">
<button type="submit">검색</button>
</form>
블로그의 정보
Hello 춘기's world
볼빵빵오춘기