[BoardController]
package com.fastcampus.ch4.controller;
import com.fastcampus.ch4.domain.*;
import com.fastcampus.ch4.service.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.ui.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.*;
import javax.servlet.http.*;
import java.time.*;
import java.util.*;
@Controller
@RequestMapping("/board")
public class BoardController {
@Autowired
BoardService boardService;
@GetMapping("/list")
public String list(int page, int pageSize, Model m, HttpServletRequest request) {
if(!loginCheck(request))
return "redirect:/login/login?toURL="+request.getRequestURL(); // 로그인을 안했으면 로그인 화면으로 이동
try {
Map map = new HashMap();
map.put("offset", (page-1)*pageSize);
map.put("pageSize", pageSize);
List<BoardDto> list = boardService.getPage(map);
m.addAttribute("list", list);
} catch (Exception e) {
e.printStackTrace();
}
return "boardList"; // 로그인을 한 상태이면, 게시판 화면으로 이동
}
private boolean loginCheck(HttpServletRequest request) {
// 1. 세션을 얻어서
HttpSession session = request.getSession();
// 2. 세션에 id가 있는지 확인, 있으면 true를 반환
return session.getAttribute("id")!=null;
}
}
[BoardDao]
package com.fastcampus.ch4.dao;
import com.fastcampus.ch4.domain.BoardDto;
import java.util.List;
import java.util.Map;
public interface BoardDao {
int count() throws Exception // T selectOne(String statement)
;
int deleteAll() // int delete(String statement)
;
int delete(Integer bno, String writer) throws Exception // int delete(String statement, Object parameter)
;
int insert(BoardDto dto) throws Exception // int insert(String statement, Object parameter)
;
List<BoardDto> selectAll() throws Exception // List<E> selectList(String statement)
;
BoardDto select(Integer bno) throws Exception // T selectOne(String statement, Object parameter)
;
List<BoardDto> selectPage(Map map) throws Exception // List<E> selectList(String statement, Object parameter)
;
int update(BoardDto dto) throws Exception // int update(String statement, Object parameter)
;
int increaseViewCnt(Integer bno) throws Exception // int update(String statement, Object parameter)
;
// int searchResultCnt(SearchCondition sc) throws Exception // T selectOne(String statement, Object parameter)
// ;
//
// List<BoardDto> searchSelectPage(SearchCondition sc) throws Exception // List<E> selectList(String statement, Object parameter)
// ;
}
[BoardDaoImpl]
package com.fastcampus.ch4.dao;
import com.fastcampus.ch4.domain.*;
import org.apache.ibatis.session.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import java.util.*;
@Repository
public class BoardDaoImpl implements BoardDao {
@Autowired
private SqlSession session;
private static String namespace = "com.fastcampus.ch4.dao.BoardMapper.";
@Override
public int count() throws Exception {
return session.selectOne(namespace+"count");
} // T selectOne(String statement)
@Override
public int deleteAll() {
return session.delete(namespace+"deleteAll");
} // int delete(String statement)
@Override
public int delete(Integer bno, String writer) throws Exception {
Map map = new HashMap();
map.put("bno", bno);
map.put("writer", writer);
return session.delete(namespace+"delete", map);
} // int delete(String statement, Object parameter)
@Override
public int insert(BoardDto dto) throws Exception {
return session.insert(namespace+"insert", dto);
} // int insert(String statement, Object parameter)
@Override
public List<BoardDto> selectAll() throws Exception {
return session.selectList(namespace+"selectAll");
} // List<E> selectList(String statement)
@Override
public BoardDto select(Integer bno) throws Exception {
return session.selectOne(namespace + "select", bno);
} // T selectOne(String statement, Object parameter)
@Override
public List<BoardDto> selectPage(Map map) throws Exception {
return session.selectList(namespace+"selectPage", map);
} // List<E> selectList(String statement, Object parameter)
@Override
public int update(BoardDto dto) throws Exception {
return session.update(namespace+"update", dto);
} // int update(String statement, Object parameter)
@Override
public int increaseViewCnt(Integer bno) throws Exception {
return session.update(namespace+"increaseViewCnt", bno);
} // int update(String statement, Object parameter)
// @Override
// public int searchResultCnt(SearchCondition sc) throws Exception {
// System.out.println("sc in searchResultCnt() = " + sc);
// System.out.println("session = " + session);
// return session.selectOne(namespace+"searchResultCnt", sc);
// } // T selectOne(String statement, Object parameter)
//
// @Override
// public List<BoardDto> searchSelectPage(SearchCondition sc) throws Exception {
// return session.selectList(namespace+"searchSelectPage", sc);
// } // List<E> selectList(String statement, Object parameter)
}
[BoardService]
package com.fastcampus.ch4.service;
import com.fastcampus.ch4.domain.BoardDto;
import java.util.List;
import java.util.Map;
public interface BoardService {
int getCount() throws Exception;
int remove(Integer bno, String writer) throws Exception;
int write(BoardDto boardDto) throws Exception;
List<BoardDto> getList() throws Exception;
BoardDto read(Integer bno) throws Exception;
List<BoardDto> getPage(Map map) throws Exception;
int modify(BoardDto boardDto) throws Exception;
// int getSearchResultCnt(SearchCondition sc) throws Exception;
//
// List<BoardDto> getSearchResultPage(SearchCondition sc) throws Exception;
}
[BoardServiceImpl]
package com.fastcampus.ch4.service;
import com.fastcampus.ch4.dao.*;
import com.fastcampus.ch4.domain.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import java.util.*;
@Service
public class BoardServiceImpl implements BoardService {
@Autowired
BoardDao boardDao;
@Override
public int getCount() throws Exception {
return boardDao.count();
}
@Override
public int remove(Integer bno, String writer) throws Exception {
return boardDao.delete(bno, writer);
}
@Override
public int write(BoardDto boardDto) throws Exception {
return boardDao.insert(boardDto);
}
@Override
public List<BoardDto> getList() throws Exception {
return boardDao.selectAll();
}
@Override
public BoardDto read(Integer bno) throws Exception {
BoardDto boardDto = boardDao.select(bno);
boardDao.increaseViewCnt(bno);
return boardDto;
}
@Override
public List<BoardDto> getPage(Map map) throws Exception {
return boardDao.selectPage(map);
}
@Override
public int modify(BoardDto boardDto) throws Exception {
return boardDao.update(boardDto);
}
// @Override
// public int getSearchResultCnt(SearchCondition sc) throws Exception {
// return boardDao.searchResultCnt(sc);
// }
//
// @Override
// public List<BoardDto> getSearchResultPage(SearchCondition sc) throws Exception {
// return boardDao.searchSelectPage(sc);
// }
}
[boardMapper.xml]
<?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">
<mapper namespace="com.fastcampus.ch4.dao.BoardMapper">
<select id="count" resultType="int">
SELECT count(*) FROM board
</select>
<delete id="deleteAll">
DELETE FROM board
</delete>
<delete id="deleteForAdmin">
DELETE FROM board WHERE bno = #{bno}
</delete>
<delete id="delete" parameterType="map">
DELETE FROM board WHERE bno = #{bno} and writer = #{writer}
</delete>
<insert id="insert" parameterType="BoardDto">
INSERT INTO board
(title, content, writer)
VALUES
(#{title}, #{content}, #{writer})
</insert>
<select id="selectAll" resultType="BoardDto">
SELECT bno, title, content, writer, view_cnt, comment_cnt, reg_date
FROM board
ORDER BY reg_date DESC, bno DESC
</select>
<sql id="selectFromBoard">
SELECT bno, title, content, writer, view_cnt, comment_cnt, reg_date
FROM board
</sql>
<select id="select" parameterType="int" resultType="BoardDto">
<include refid="selectFromBoard"/>
WHERE bno = #{bno}
</select>
<select id="selectPage" parameterType="map" resultType="BoardDto">
<include refid="selectFromBoard"/>
ORDER BY reg_date DESC, bno DESC
LIMIT #{offset}, #{pageSize}
</select>
<update id="update" parameterType="BoardDto">
UPDATE board
SET title = #{title}
, content = #{content}
, up_date = now()
WHERE bno = #{bno}
</update>
<update id="updateCommentCnt" parameterType="map">
UPDATE board
SET comment_cnt = comment_cnt + #{cnt}
WHERE bno = #{bno}
</update>
<update id="increaseViewCnt" parameterType="int">
UPDATE board
SET view_cnt = view_cnt + 1
WHERE bno = #{bno}
</update>
</mapper>
[boardList.jsp]
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>fastcampus</title>
<link rel="stylesheet" href="<c:url value='/css/menu.css'/>">
</head>
<body>
<div id="menu">
<ul>
<li id="logo">fastcampus</li>
<li><a href="<c:url value='/'/>">Home</a></li>
<li><a href="<c:url value='/board/list'/>">Board</a></li>
<li><a href="<c:url value='/login/login'/>">login</a></li>
<li><a href="<c:url value='/register/add'/>">Sign in</a></li>
<li><a href=""><i class="fas fa-search small"></i></a></li>
</ul>
</div><div style="text-align:center">
<table border="1">
<tr>
<th>번호</th>
<th>제목</th>
<th>이름</th>
<th>등록일</th>
<th>조회수</th>
</tr>
<c:forEach var="board" items="${list}">
<tr>
<th>${board.bno}</th>
<th>${board.title}</th>
<th>${board.writer}</th>
<th>${board.reg_date}</th>
<th>${board.view_cnt}</th>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
이전 코드에서 다음과 같이 추가로 파일을 생성 및 수정하고 서버를 실행하여 실습을 진행한다.
실행한 서버에 http://localhost/ch4/board/list?page=1&pageSize=10값을 입력
user_info 테이블에 있는 로그인 정보를 통해 로그인을 진행한다.

BoardDaoImplTest클래스에 데이터를 삽입하는 메서드를 생성해 데이터를 넣어보자.
(강의에서는 1개만 나왔었는데, 수행했을때는 여러개가 나왔다)

insert 테스트가 잘 통과된것을 확인할 수 있다.

실행한 결과를 다시 확인하면 다음과 같다.
처음에 서버를 실행했을 때 URL에 값을 안주면, 서버 에러가 발생했었다.
이런 에러를 잡기 위해 BoardController의 list 매개변수 타입 int를 -> Integer로 바꿔준다.


Integer로 하면, 값이 없어도 위와 같은 에러가 발생하지 않는다.

Integer로 수정 후 서버를 재실행한 다음 Board로 이동하니 아까와 같은 서버 에러가 발생하지 않는다.
(int였을 때 데이터가 없으면 null로 처리되어 에러가 발생한다?)
- 이번에는 밑에 내비게이션을 넣어보자. 아까 생성한 PageHandler를 사용한다.

PageHandler가 값들을 다 계산해서 가지고 있기 때문에 PageHandler를 jsp로 넘겨주면, jsp에서 PageHandler에 있는
값을 가지고 페이징을 해주면 된다.


성공!! 중간에 attributeName을 잘못줘서 찾느라 오래 걸렸다..

이런식으로 내비게이션을 생성해서 페이지를 이동할 수 있다!
+ 이전 페이지로 이동이 안됐었는데, PageHandler를 다음과 같이 수정해준다.

'Spring' 카테고리의 다른 글
| ch4 06. 게시판 읽기, 쓰기, 삭제, 수정 기능 구현(2) (0) | 2023.03.21 |
|---|---|
| ch4 05. 게시판 읽기, 쓰기, 삭제, 수정 기능 구현(1) (0) | 2023.03.21 |
| ch4 03. 게시판 목록 만들기와 페이징 - TDD (1) (0) | 2023.03.17 |
| ch04 02. Mybatis로 DAO 작성하기 (0) | 2023.03.16 |
| ch4 01. MyBatis의 소개와 설정 (0) | 2023.03.16 |