728x90
반응형
게시판 목록 조회 화면에 페이징 기능을 추가합니다.
2023-01-20 선택된 페이지 번호를 굵게 표시하도록 수정
sql-board.xml
기존 목록 조회 쿼리에 지정된 위치로부터 10개씩 데이터를 가져오도록 limit 구문을 추가합니다. 그리고, 검색 조건과 일치하는 전체 게시물 개수를 가져오는 쿼리를 추가합니다.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="board.mapper.BoardMapper">
<select id="selectBoardListForSample" resultType="board.dto.BoardDto">
select board_idx, title, hit_cnt,
date_format(created_dt, '%Y-%m-%d %H:%i:%s') as created_dt
from t_board
where deleted_yn = 'N'
order by board_idx desc
limit 4;
</select>
<!-- 검색 조건과 일치하는 게시물 개수를 조회 -->
<select id="selectBoardListCount" resultType="int">
select count(*)
from t_board
where deleted_yn = 'N'
</select>
<!-- 페이징 처리 -->
<select id="selectBoardList" parameterType="int" resultType="board.dto.BoardDto">
select board_idx, title, hit_cnt,
date_format(created_dt, '%Y-%m-%d %H:%i:%s') as created_dt
from t_board
where deleted_yn = 'N'
order by board_idx desc
limit #{offset}, 10
</select>
<insert id="insertBoard" parameterType="board.dto.BoardDto">
insert into t_board (title, contents, created_dt, created_id)
values ( #{title}, #{contents}, now(), #{createdId} )
</insert>
<update id="updateHitCount" parameterType="int">
update t_board
set hit_cnt = hit_cnt + 1
where board_idx = #{boardIdx}
</update>
<select id="selectBoardDetail" parameterType="int" resultType="board.dto.BoardDto">
select board_idx, title, contents, hit_cnt,
date_format(created_dt, '%Y-%m-%d %H:%i:%s') as created_dt,
created_id
from t_board
where deleted_yn = 'N' and board_idx = #{boardIdx}
</select>
<update id="updateBoard" parameterType="board.dto.BoardDto">
update t_board
set title = #{title},
contents = #{contents},
updated_dt = now(),
updated_id = #{updatedId}
where board_idx = #{boardIdx}
</update>
<delete id="deleteBoard" parameterType="int">
update t_board
set deleted_yn = 'Y',
updated_dt = now(),
updated_id = #{updatedId}
where board_idx = #{boardIdx}
</delete>
</mapper>
BoardMapper.java
전체 게시물 개수를 조회하는 메서드를 추가하고, 게시물 조회 메서드를 수정합니다.
package board.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import board.dto.BoardDto;
@Mapper
public interface BoardMapper {
List<BoardDto> selectBoardListForSample() throws Exception;
// 메서드 추가: 검색 조건과 일치하는 게시판 개수를 반환
int selectBoardListCount() throws Exception;
// 메서드 수정: 검색 조건과 일치하는 게시판 중 offset에서 부터 10개만 조회해서 반환
List<BoardDto> selectBoardList(int offset) throws Exception;
void insertBoard(BoardDto boardDto) throws Exception;
void updateHitCount(int boardIdx) throws Exception;
BoardDto selectBoardDetail(int boardIdx) throws Exception;
void updateBoard(BoardDto boardDto) throws Exception;
void deleteBoard(int boardIdx) throws Exception;
}
BoardService.java
전체 게시물 개수를 조회하는 메서드를 추가하고, 게시물 조회 메서드를 수정합니다.
package board.service;
import java.util.List;
import board.dto.BoardDto;
public interface BoardService {
public List<BoardDto> selectBoardListForSample() throws Exception;
// 메서드 추가
int selectBoardListCount() throws Exception;
// 메서드 수정
public List<BoardDto> selectBoardList(int offset) throws Exception;
public void insertBoard(BoardDto boardDto) throws Exception;
public BoardDto selectBoardDetail(int boardIdx) throws Exception;
void updateBoard(BoardDto boardDto) throws Exception;
void deleteBoard(int boardIdx) throws Exception;
}
BoardServiceImpl.java
전체 게시물 개수를 조회하는 메서드를 추가하고, 게시물 조회 메서드를 수정합니다.
package board.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import board.dto.BoardDto;
import board.mapper.BoardMapper;
@Service
public class BoardServiceImpl implements BoardService {
@Autowired
private BoardMapper boardMapper;
// 메서드 추가
@Override
public int selectBoardListCount() throws Exception {
return boardMapper.selectBoardListCount();
}
// 메서드 수정
@Override
public List<BoardDto> selectBoardList(int offset) throws Exception {
return boardMapper.selectBoardList(offset);
}
@Override
public void insertBoard(BoardDto boardDto) throws Exception {
boardMapper.insertBoard(boardDto);
}
@Override
public BoardDto selectBoardDetail(int boardIdx) throws Exception {
boardMapper.updateHitCount(boardIdx);
return boardMapper.selectBoardDetail(boardIdx);
}
@Override
public void deleteBoard(int boardIdx) throws Exception {
boardMapper.deleteBoard(boardIdx);
}
@Override
public List<BoardDto> selectBoardListForSample() throws Exception {
return boardMapper.selectBoardListForSample();
}
@Override
public void updateBoard(BoardDto boardDto) throws Exception {
boardMapper.updateBoard(boardDto);
}
}
BoardController.java
게시판 조회 시 읽어올 게시물의 범위를 지정하고, 전체 게시물의 개수를 조회해서 페이지의 개수를 계산해서 뷰로 전달하도록 수정합니다.
package board.controller;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import board.dto.BoardDto;
import board.dto.UserDto;
import board.service.BoardService;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Controller
public class BoardController {
// private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private BoardService boardService;
@GetMapping("/board/openBoardList.do")
public ModelAndView openBoardList(
// 현재 페이지 번호를 요청 파라미터로 부터 추출
@RequestParam(value="currentPage", required=false, defaultValue="1") int currentPage) throws Exception {
ModelAndView mv = new ModelAndView("/board/boardList");
List<BoardDto> list = boardService.selectBoardList((currentPage - 1) * 10);
mv.addObject("list", list);
// 페이징 정보 출력에 사용되는 변수
mv.addObject("pageCount", Math.ceil(boardService.selectBoardListCount() / 10.0));
mv.addObject("currentPage", currentPage);
return mv;
}
@GetMapping("/board/openBoardWrite.do")
public String openBoardWrite(HttpSession session) throws Exception {
return "/board/boardWrite";
}
@PostMapping("/board/insertBoard.do")
public String insertBoard(BoardDto boardDto, HttpSession session) throws Exception {
UserDto userDto = (UserDto)session.getAttribute("user");
boardDto.setCreatedId(userDto.getUserId());
boardService.insertBoard(boardDto);
return "redirect:/board/openBoardList.do";
}
@GetMapping("/board/openBoardDetail.do")
public ModelAndView openBoardDetail(@RequestParam int boardIdx) throws Exception {
ModelAndView mv = new ModelAndView("/board/boardDetail");
BoardDto boardDto = boardService.selectBoardDetail(boardIdx);
mv.addObject("board", boardDto);
return mv;
}
@PostMapping("/board/updateBoard.do")
public String updateBoard(BoardDto boardDto, HttpSession session) throws Exception {
UserDto userDto = (UserDto)session.getAttribute("user");
boardDto.setUpdatedId(userDto.getUserId());
boardService.updateBoard(boardDto);
return "redirect:/board/openBoardList.do";
}
@PostMapping("/board/deleteBoard.do")
public String deleteBoard(BoardDto boardDto, HttpSession session) throws Exception {
UserDto userDto = (UserDto)session.getAttribute("user");
boardDto.setUpdatedId(userDto.getUserId());
boardService.deleteBoard(boardDto.getBoardIdx());
return "redirect:/board/openBoardList.do";
}
}
boardList.html
페이지 번호와 링크를 출력하도록 수정합니다.
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>게시판</title>
<link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body>
<div class="container">
<div th:if="${#strings.isEmpty(session.user)}" style="text-align:right;">
<a href="/login.do" class="btn">login</a>
</div>
<div th:unless="${#strings.isEmpty(session.user)}" style="text-align:right;">
<b>[[${session.user.userName}]]</b>님 환영합니다. <a href="/logout.do" class="btn">logout</a>
</div>
<h2>게시판 목록</h2>
<table class="board_list">
<colgroup>
<col width="15%" />
<col width="*" />
<col width="15%" />
<col width="20%" />
</colgroup>
<thead>
<tr>
<th scope="col">글번호</th>
<th scope="col">제목</th>
<th scope="col">조회수</th>
<th scope="col">작성일</th>
</tr>
</thead>
<tbody>
<tr th:if="${#lists.size(list)} > 0" th:each="board : ${list}">
<td th:text="${board.boardIdx}"></td>
<!--
<td th:text="${board.title}" class="title"></td>
-->
<td class="title">
<a href="/board/openBoardDetail.do?boardIdx="
th:attrappend="href=${board.boardIdx}"
th:text="${board.title}"></a>
</td>
<td th:text="${board.hitCnt}"></td>
<td th:text="${board.createdDt}"></td>
</tr>
<tr th:unless="${#lists.size(list)} > 0">
<td colspan="4">조회된 결과가 없습니다.</td>
</tr>
</tbody>
</table>
<a href="/board/openBoardWrite.do" class="btn">글쓰기</a>
<!-- 페이지 번호와 링크를 출력 -->
<style>
ul { margin: 0; padding: 0; list-style: none; float: right; }
li { float: left; width: auto; }
li a { display: block; margin-right: 5px; padding: 3px 15px; border-radius: 2px; background-color: #86ecf8; color: #ffffff; font-size: 12px; text-decoration: none; }
li a:hover { background-color: #94ecf6; }
ul:after { content: ""; display: block; clear: both; }
li a.current { font-weight: bold; background-color: #75dbe7; }
</style>
<ul>
<li th:each="i : ${#numbers.sequence(1, pageCount, 1)}">
<a th:if="${i eq currentPage}" class="current" href="openBoardList.do?currentPage=" th:attrappend="href=${i}">[[${i}]]</a>
<a th:unless="${i eq currentPage}" href="openBoardList.do?currentPage=" th:attrappend="href=${i}">[[${i}]]</a>
</li>
</ul>
</div>
</body>
</html>
결과 화면
728x90
반응형
'수업자료' 카테고리의 다른 글
20230131 실습내용 (0) | 2023.02.01 |
---|---|
20230126 실습내용 (0) | 2023.01.26 |
세션으로부터 로그인한 사용자 정보를 가져와서 활용 (0) | 2023.01.13 |
로그인, 로그아웃 기능 추가 (0) | 2023.01.11 |
20230110 실습내용 (0) | 2023.01.10 |
댓글