2019.08.08

 

 

 

 

 페이징 처리를 위한 쿼리 (Model)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
                        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
    <!-- SELECT 쿼리 -->
    <select id="boardList" parameterType="java.util.Map" resultType="kr.or.ksmart.ksmart_layout1.vo.Board">
        SELECT 
              board_no        AS boardNo
            , board_user     AS boardUser
            , board_pw        AS boardPw
            , board_title    AS boardTitle
            , board_content    AS boardContent
            , board_date    AS boardDate
        FROM board 
    
        <!-- 메서드 오버로딩으로 다른 메서드를 호출하기 위해 개인적으로 걸어놓은 조건문 -->
        <if test="boardNo neq null and boardNo neq ''.toString()">
            WHERE board_no = #{boardNo}
        </if>
 
        <!-- 다른 메서드 호출시 반영되지 않기위해 걸어놓은 조건문 -->
        <if test="startRow neq lastPage"> 
            ORDER BY board_no DESC
            LIMIT #{startRow},#{rowPerPage}
        </if>
    </select>
 
</mapper>
 

 

 페이징 알고리즘 (Model)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
 
 
 
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
 
@Service
@Transactional
public class BoardService {
 
    @Autowired private BoardMapper boardMapper;
    
    // paging
    public Map<String, Object> boardList(int currentPage){
        
        // 페이지에 보여줄 행의 개수 ROW_PER_PAGE = 10으로 고정
        final int ROW_PER_PAGE = 10
        
        // 페이지에 보여줄 첫번째 페이지 번호는 1로 초기화
        int startPageNum = 1;
        
        // 처음 보여줄 마지막 페이지 번호는 10
        int lastPageNum = ROW_PER_PAGE;
        
        // 현재 페이지가 ROW_PER_PAGE/2 보다 클 경우
        if(currentPage > (ROW_PER_PAGE/2)) {
            // 보여지는 페이지 첫번째 페이지 번호는 현재페이지 - ((마지막 페이지 번호/2) -1 )
            // ex 현재 페이지가 6이라면 첫번째 페이지번호는 2
            startPageNum = currentPage - ((lastPageNum/2)-1);
            // 보여지는 마지막 페이지 번호는 현재 페이지 번호 + 현재 페이지 번호 - 1 
            lastPageNum += (startPageNum-1);
        }
        
        // Map Data Type 객체 참조 변수 map 선언
        // HashMap() 생성자 메서드로 새로운 객체를 생성, 생성된 객체의 주소값을 객체 참조 변수에 할당
        Map<String, Integer> map = new HashMap<String, Integer>();
        // 한 페이지에 보여지는 첫번째 행은 (현재페이지 - 1) * 10
        int startRow = (currentPage - 1)*ROW_PER_PAGE;
        // 값을 map에 던져줌
        map.put("startRow", startRow);
        map.put("rowPerPage", ROW_PER_PAGE);
        
        // DB 행의 총 개수를 구하는 getBoardAllCount() 메서드를 호출하여 double Date Type의 boardCount 변수에 대입
        double boardCount = boardMapper.getBoardAllCount();
        
        // 마지막 페이지번호를 구하기 위해 총 개수 / 페이지당 보여지는 행의 개수 -> 올림 처리 -> lastPage 변수에 대입
        int lastPage = (int)(Math.ceil(boardCount/ROW_PER_PAGE));
        
        // 현재 페이지가 (마지막 페이지-4) 보다 같거나 클 경우
        if(currentPage >= (lastPage-4)) {
            // 마지막 페이지 번호는 lastPage
            lastPageNum = lastPage;
        }
        
        // 구성한 값들을 Map Date Type의 resultMap 객체 참조 변수에 던져주고 return
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("list", boardMapper.boardList(map));
        resultMap.put("currentPage", currentPage);
        resultMap.put("lastPage", lastPage);
        resultMap.put("startPageNum", startPageNum);
        resultMap.put("lastPageNum", lastPageNum);
        return resultMap;
    }
 

 

 

 

 

 페이징 메서드 호출하는 컨트롤러 (Controller)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 
 
 
import org.springframework.stereotype.Controller;
 
 
@Controller
public class BoardController {
 
    @Autowired private BoardService boardService;
 
    // currentPage 변수를 받는데 없을 경우 default 값을 1로 받음
    @GetMapping("/boardList")
    public String boardList(Model model, @RequestParam(value = "currentPage", required = false, defaultValue = "1"int currentPage) {
        Map<String, Object> map = boardService.boardList(currentPage);
        model.addAttribute("boardList"map.get("list"));
        model.addAttribute("currentPage"map.get("currentPage"));
        model.addAttribute("lastPage"map.get("lastPage"));
        model.addAttribute("startPageNum"map.get("startPageNum"));
        model.addAttribute("lastPageNum"map.get("lastPageNum"));
        return "board/blist/boardList";
    }
 

 

 화면 (View)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
 
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" 
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/default}">
 
<th:block layout:fragment="customTitle">
    <title> 게시판 목록 </title>
</th:block>
<th:block layout:fragment="customContents">
    <div class="text-right">
        <br/>
        <a th:href="@{/addBoard}">게시글 등록</a>
    </div>
    <br/>
    <table border = "1" style="width:100%">
        <tr class="text-center">
            <th style="width: 5%">NO</th>
            <th style="width: 70%">제목</th>
            <th>글쓴이</th>
            <th style="width: 12%">등록날짜</th>
        </tr>
        <tr th:each="list : ${boardList}">
            <td th:text="${list.boardNo}"></td>
            <td><a th:href="@{/boardView(boardNo=${list.boardNo})}" 
                   th:text="${#strings.abbreviate(list.boardTitle,50)}"></a></td>
            <td th:text="${list.boardUser}"></td>
            <td th:text="${list.boardDate}"></td>
        </tr>
    </table>
    <br/>
    <div class="text-center">
    <span><a th:href="@{/boardList(currentPage=1)}">처음</a></span>
    
    <!-- 현재 페이지가 1보다 클 경우 이전 href, 1보다 작은 경우 이전 text -->
    <span th:if="${currentPage > 1}"><a th:href="@{/boardList(currentPage=(${currentPage}-1))}">이전</a></span>
    <span th:unless="${currentPage > 1}" th:text="이전"></span>
    
    <!-- #number.sequence 인수로 지정한 2개의 수 범위에서 배열을 생성 -->
    <th:block th:each="num : ${#numbers.sequence(startPageNum,lastPageNum)}">
        <span th:if="${currentPage == num}" th:text="${'['+ num + ']'}"></span>
        <a th:unless="${currentPage == num}" th:text="${'['+ num + ']'}" th:href="@{/boardList(currentPage=${num})}"></a>
    </th:block>
    
    <!-- 현재 페이지가 마지막페이지와 같지 않을 경우 다음 href, 같을 경우 다음 text -->
    <span th:if="${currentPage != lastPage}"><a th:href="@{/boardList(currentPage=(${currentPage}+1))}">다음</a></span>
    <span th:unless="${currentPage != lastPage}" th:text="다음"></span>
    <span><a th:href="@{/boardList(currentPage=${lastPage})}">마지막</a></span>
    </div>
    <br/>
    <form action="/boardList" method="post" class="text-center">
        <select name="sk">
            <option value="board_title">제목</option>
            <option value="board_content">내용</option>
            <option value="board_user">글쓴이</option>
        </select>
        <input type="text" name="sv">
        <button type="submit">검색</button>
    </form>        
</th:block>
</html>
 

 

 

 

실행 화면

 

 

+ Recent posts