본문 바로가기

서버/SprintBoot
[스프링부트(Spring Boot)] 검색 기능 구현

// 검색

- BoardRepository 인터페이스에 메소드 추가

package com.study.board.repository;

import com.study.board.entity.Board;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface BoardRepository extends JpaRepository<Board, Integer> {

    Page<Board> findByTitleContaining(String searchKeyword, Pageable pageable);
}


- BoardServicee 에 메소드 추가

public Page<Board> boardSerchList(String searchKeyword, Pageable pagealbe) {

	return boardRepository.findByTitleContaining(searchKeyword, pagealbe);
}


- BoardController에 조건문 처리

@GetMapping("/board/list")
public String boardList(Model model,						
                        @PageableDefault(page = 0, size = 10, sort = "id", direction = Sort.Direction.DESC) Pageable pagable,
                        String searchKeyword) {

    Page<Board> list = null;

    if(searchKeyword != null) {
        list = boardService.boardSerchList(searchKeyword, pagable);
    } else {
    	list = boardService.boardList(pagable);
    }

    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에서 페이징 처리에서 매개변수 넘기기 + 검색 창 생성

<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>