결과
- 게시글 수정 시 작성자는 고정되게 했다.
- 한 페이지 당 게시글 5개를 담을 수 있으며 넘는다면 페이지 넘길 수 있다.
- 게시글에서 목록으로 넘어갈 시 페이지 유지
- 게시글 삭제 세 페이지 유지
- 게시글 수정 시 수정된 게시글 다시 출력
springMVC 프로젝트와 MyBatis 연동
https://yeo-computerclass.tistory.com/317
[mybatis] springMVC + MyBatis 연동 (스프링MVC + 마이바티스)
pom.xml에 라이브러리 설정 ▶pom.xml (부분) org.mybatis mybatis 3.4.6 org.mybatis mybatis-spring 1.3.2 org.springframework spring-jdbc 5.0.2.RELEASE mysql mysql-connector-java 8.0.27 DB는 자신이 쓰는..
yeo-computerclass.tistory.com
설정 및 Project Explorer 경로
위에 springMVC + MyBatis 연동 포스팅만 봐도 충분하지만
댓글 기능과 합쳐서 만든 설정을 댓글 기능 포스팅에 올리도록 하겠다.
https://yeo-computerclass.tistory.com/336
게시판 댓글 추가/삭제/List (Ajax 이용)
Project Explorer 설정들 JSON 설정 https://yeo-computerclass.tistory.com/299 JSON 설정에 관한 자세한 내용을 보려면 이를 참고 ▶pom.xml 추가 태그에 추가 2.9.5 태그에 추가 com.fasterxml.jackson.core j..
yeo-computerclass.tistory.com
테이블 생성
▶board (게시글)
CREATE TABLE board(
id BIGINT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
writer VARCHAR(30) NOT NULL,
view int DEFAULT 0,
regist_datetime DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
modify_datetime DATETIME
);
DTO 생성
▶Board.java
package com.spring.boardapp.domain;
public class Board {
private String id;
private String title;
private String content;
private String writer;
private String views;
private String regist_datetime;
private String modify_datetime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getViews() {
return views;
}
public void setViews(String views) {
this.views = views;
}
public String getRegist_datetime() {
return regist_datetime;
}
public void setRegist_datetime(String regist_datetime) {
this.regist_datetime = regist_datetime;
}
public String getModify_datetime() {
return modify_datetime;
}
public void setModify_datetime(String modify_datetime) {
this.modify_datetime = modify_datetime;
}
}
▶Paging.java
package com.spring.boardapp.domain.paging;
public class Paging {
private int pageNum; //현재 페이지
private int pageAmount; //한 페이지당 출력되는 게시글 수
private int startPage;
private int endPage;
private boolean prev;
private boolean next;
private int total;
private String searchType;
private String searchWord;
public Paging(int pageNum, int pageAmount, String searchType, String searchWord, int total) {
this.pageNum = pageNum;
this.pageAmount = pageAmount;
this.searchType = searchType;
this.searchWord = searchWord;
this.total = total;
//끝 페이지
this.endPage = (int) Math.ceil((this.pageNum)/5.0) * 5;
//시작 페이지
this.startPage = this.endPage - 4;
//아예 페이지
int tmpEndPage = (int)Math.ceil((total*1.0)/pageAmount);
if(this.endPage > tmpEndPage) this.endPage = tmpEndPage;
this.prev = this.startPage > 1;
this.next = this.endPage < tmpEndPage;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageAmount() {
return pageAmount;
}
public void setPageAmount(int pageAmount) {
this.pageAmount = pageAmount;
}
public int getStartPage() {
return startPage;
}
public void setStartPage(int startPage) {
this.startPage = startPage;
}
public int getEndPage() {
return endPage;
}
public void setEndPage(int endPage) {
this.endPage = endPage;
}
public boolean isPrev() {
return prev;
}
public void setPrev(boolean prev) {
this.prev = prev;
}
public boolean isNext() {
return next;
}
public void setNext(boolean next) {
this.next = next;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public String getSearchType() {
return searchType;
}
public void setSearchType(String searchType) {
this.searchType = searchType;
}
public String getSearchWord() {
return searchWord;
}
public void setSearchWord(String searchWord) {
this.searchWord = searchWord;
}
}
Controller 생성
package com.spring.boardapp.controller;
...
@Controller
@RequestMapping("/board")
public class BoardController {
@Resource(name = "boardService")
private BoardService boardService;
@RequestMapping(value = "/regist")
public String registBoard(@RequestParam Map<String, Object> paramMap, Model model) {
if (paramMap.isEmpty())
return "board/boardRegister";
else {
int result = boardService.insertBoard(paramMap);
if (result > 0)
return "redirect:/board/list";
else
return "/board/boardRegister";
}
}
@RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
public String getBoard(@PathVariable String id,@RequestParam String pageNum, @RequestParam String pageAmount,
@RequestParam(required=false) String searchType, @RequestParam(required=false) String searchWord,Model model) {
Board board = boardService.getBoardDetail(id);
if (board == null)
return "board/boardList";
else {
model.addAttribute("board", board);
model.addAttribute("pageNum", pageNum);
model.addAttribute("pageAmount", pageAmount);
model.addAttribute("searchType",searchType);
model.addAttribute("searchWord",searchWord);
return "board/boardDetail";
}
}
@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
public String updateBoard(@PathVariable String id,@RequestParam String pageNum, @RequestParam String pageAmount, Model model) {
model.addAttribute("board",boardService.getBoardDetail(id));
model.addAttribute("pageNum", pageNum);
model.addAttribute("pageAmount", pageAmount);
return "board/boardEdit";
}
@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
public String updateBoard(@RequestParam Map<String, Object> paramMap) {
boardService.updateBoard(paramMap);
String pageNum = (String) paramMap.get("pageNum");
String pageAmount = (String) paramMap.get("pageAmount");
return "redirect:/board/detail/{id}?pageNum="+pageNum+"&pageAmount="+pageAmount;
}
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public String deleteBoard(@PathVariable String id,@RequestParam String pageNum, @RequestParam String pageAmount) {
boardService.deleteBoard(id);
return "redirect:/board/list?pageNum="+pageNum+"&pageAmount="+pageAmount;
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String getBoardList(@RequestParam(required = false) String pageNum, @RequestParam(required = false) String pageAmount,
@RequestParam(required=false) String searchType, @RequestParam(required=false) String searchWord, Model model) {
if(pageNum==null) pageNum="1";
if(pageAmount==null) pageAmount="5";
if(searchType==null) searchType="";
if(searchWord==null) searchWord="";
Map<String, Object> map = new HashMap<String, Object>();
map.put("pageNum", Integer.parseInt(pageNum));
map.put("pageAmount", Integer.parseInt(pageAmount));
map.put("searchWord", searchWord);
map.put("searchType", searchType);
List<Board> boardList = boardService.getBoardListWithPaging(map);
int total = boardService.getBoardTotalCnt(map);
model.addAttribute("boardList", boardList);
Paging paging = new Paging(Integer.parseInt(pageNum), Integer.parseInt(pageAmount), searchType, searchWord, total);
model.addAttribute("pageMaker", paging);
return "board/boardList";
}
}
DAO 생성
▶인터페이스
package com.spring.boardapp.dao;
import java.util.List;
import java.util.Map;
import com.spring.boardapp.domain.Board;
import com.spring.boardapp.domain.Reply;
import com.spring.boardapp.domain.paging.Paging;
public interface BoardDao {
// 게시글 삽입
int insertBoard(Map<String, Object> paramMap);
// 게시글 읽기
Board getBoardDetail(String id);
// 게시글 수정
int updateBoard(Map<String, Object> paramMap);
// 게시글 삭제
int deleteBoard(String id);
// 게시글 List
List<Board> getBoardList();
// 페이징 게시글 List
List<Board> getBoardListWithPaging(Map<String, Object> paramMap);
// 게시글 전체 수
int getBoardTotalCnt(Map<String, Object> paramMap);
// 조회수 증가
int updateBoardViews(String id);
}
▶Impl
package com.spring.boardapp.dao;
...
@Repository("boardDao")
public class BoardDaoImpl implements BoardDao {
@Autowired
private SqlSession sqlSession;
@Override
public int insertBoard(Map<String, Object> paramMap) {
return sqlSession.insert("insertBoard", paramMap);
}
@Override
public Board getBoardDetail(String id) {
return sqlSession.selectOne("selectBoard", id);
}
@Override
public int updateBoard(Map<String, Object> paramMap) {
// TODO Auto-generated method stub
return sqlSession.update("updateBoard", paramMap);
}
@Override
public int deleteBoard(String id) {
// TODO Auto-generated method stub
return sqlSession.delete("deleteBoard", id);
}
@Override
public List<Board> getBoardList() {
// TODO Auto-generated method stub
return sqlSession.selectList("selectBoardList");
}
@Override
public List<Board> getBoardListWithPaging(Map<String, Object> paramMap) {
// TODO Auto-generated method stub
System.out.println("DAO");
System.out.println(paramMap.get("searchType"));
System.out.println(paramMap.get("searchWord"));
return sqlSession.selectList("selectBoardListWithPaging", paramMap);
}
@Override
public int getBoardTotalCnt(Map<String, Object> paramMap) {
// TODO Auto-generated method stub
return sqlSession.selectOne("getBoardTotalCnt", paramMap);
}
@Override
public int updateBoardViews(String id) {
// TODO Auto-generated method stub
return sqlSession.update("updateBoardViews", id);
}
}
Service
▶인터페이스
package com.spring.boardapp.service;
...
public interface BoardService {
// 게시글 등록
int insertBoard(Map<String, Object> paramMap);
// 게시글 상세보기
Board getBoardDetail(String id);
// 게시글 수정
boolean updateBoard(Map<String, Object> paramMap);
// 게시글 삭제
boolean deleteBoard(String id);
// 게시글 List
List<Board> getBoardList();
// 게시글 페이징 List
List<Board> getBoardListWithPaging(Map<String, Object> paramMap);
// 게시글 전체 개수
int getBoardTotalCnt(Map<String, Object> paramMap);
}
▶Impl
package com.spring.boardapp.service;
...
@Service("boardService")
public class BoardServiceImpl implements BoardService {
@Resource(name = "boardDao")
private BoardDao boardDao;
@Override
public int insertBoard(Map<String, Object> paramMap) {
// TODO Auto-generated method stub
if (paramMap.get("title") == null || paramMap.get("writer") == null) {
return 0;
} else {
int result = boardDao.insertBoard(paramMap);
return result;
}
}
@Override
public Board getBoardDetail(String id) {
boardDao.updateBoardViews(id);
return boardDao.getBoardDetail(id);
}
@Override
public boolean updateBoard(Map<String, Object> paramMap) {
int result = boardDao.updateBoard(paramMap);
if(result == 1) return true;
else return false;
}
@Override
public boolean deleteBoard(String id) {
if(boardDao.deleteBoard(id)==1) return true;
else return false;
}
@Override
public List<Board> getBoardList() {
// TODO Auto-generated method stub
return boardDao.getBoardList();
}
@Override
public List<Board> getBoardListWithPaging(Map<String, Object> paramMap) {
int startBoardNum = ((Integer)paramMap.get("pageNum")-1) * (Integer)paramMap.get("pageAmount");
paramMap.put("startBoardNum", startBoardNum);
return boardDao.getBoardListWithPaging(paramMap);
}
@Override
public int getBoardTotalCnt(Map<String, Object> paramMap) {
// TODO Auto-generated method stub
return boardDao.getBoardTotalCnt(paramMap);
}
}
board.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.spring.boardapp.dao.BoardDao">
<insert id="insertBoard" parameterType="java.util.HashMap">
INSERT INTO board(
title,
content,
writer,
views
)
values(
#{title},
#{content},
#{writer},
0
)
</insert>
<select id="selectBoard" parameterType="String" resultType="Board">
SELECT id,
title,
content,
writer,
views,
date_format(regist_datetime, '%Y-%m-%d %H:%i:%s') regist_datetime,
date_format(modify_datetime, '%Y-%m-%d %H:%i:%s') modify_datetime
FROM board
WHERE id = #{id}
</select>
<update id="updateBoard" parameterType="java.util.HashMap">
UPDATE board
SET title = #{title},
content = #{content},
modify_datetime = NOW()
WHERE id = #{id}
</update>
<delete id="deleteBoard" parameterType="String">
DELETE FROM board
WHERE id = #{id}
</delete>
<select id="selectBoardList" resultType="Board">
SELECT id,
title,
content,
writer,
views,
date_format(regist_datetime, '%Y-%m-%d %H:%i:%s') regist_datetime,
date_format(modify_datetime, '%Y-%m-%d %H:%i:%s') modify_datetime
FROM board
ORDER BY id
LIMIT 10 OFFSET 0
</select>
<select id="selectBoardListWithPaging" parameterType = "java.util.HashMap" resultType="Board">
SELECT id,
title,
content,
writer,
views,
date_format(regist_datetime, '%Y-%m-%d %H:%i:%s') regist_datetime,
date_format(modify_datetime, '%Y-%m-%d %H:%i:%s') modify_datetime
FROM (
SELECT *
FROM board
WHERE <if test="searchType=='title'">title LIKE CONCAT('%',#{searchWord},'%')</if>
<if test="searchType=='writer'">writer LIKE CONCAT('%',#{searchWord},'%')</if>
<if test="searchType=='content'">content LIKE CONCAT('%',#{searchWord},'%')</if>
<if test="searchType=='tc'">title LIKE CONCAT('%',#{searchWord},'%') OR content LIKE CONCAT('%',#{searchWord},'%')</if>
<if test="searchType==''">1=1</if>
) A
ORDER BY regist_datetime DESC, id DESC
LIMIT #{pageAmount} OFFSET #{startBoardNum}
</select>
<select id="getBoardTotalCnt" parameterType = "java.util.HashMap" resultType="int">
SELECT COUNT(*)
FROM board
WHERE <if test="searchType=='title'.toString()">title LIKE CONCAT('%',#{searchWord},'%')</if>
<if test="searchType=='writer'.toString()">writer LIKE CONCAT('%',#{searchWord},'%')</if>
<if test="searchType=='content'.toString()">content LIKE CONCAT('%',#{searchWord},'%')</if>
<if test="searchType=='tc'.toString()">title LIKE CONCAT('%',#{searchWord},'%') OR content LIKE CONCAT('%',#{searchWord},'%')</if>
<if test="searchType==''.toString()">1=1</if>
</select>
<update id="updateBoardViews" parameterType="String">
UPDATE board
SET views = views + 1
WHERE id = #{id}
</update>
</mapper>
View
▶boardDetail
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!-- jquery -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
h1, h2 {
text-align: center;
}
table {
margin: auto;
}
</style>
<title>게시글(${board.id })</title>
</head>
<body>
<h1>게시글(${board.id })</h1>
<table width="930px">
<tr>
<td align="left">
<%-- <form value = "목록" action="/list?pageNum=${pageMaker.pageNum }&pageAmount=${pageMaker.pageAmount}"></form> --%>
<input type="button" value="목록"
onclick="location.href='/board/list?searchType=${searchType }&searchWord=${searchWord }&pageNum=${pageNum }&pageAmount=${pageAmount}'">
</td>
<td align="right"><div>
<input type="button" value="수정"
onclick="location.href='/board/edit/${board.id}?pageNum=${pageNum }&pageAmount=${pageAmount}'">
<input type="button" value="삭제"
onclick="location.href='/board/delete/${board.id}?pageNum=${pageNum }&pageAmount=${pageAmount}'">
</div></td>
</tr>
</table>
<table border="1" width="930px">
<tr>
<td width="700px"><b>${board.title }</b></td>
<td align="left"><div>
등록: ${board.regist_datetime }<br /> 수정: ${board.modify_datetime }
</div></td>
</tr>
<tr>
<td align="left" width="700px">${board.writer }</td>
<td>조회 수 ${board.views }</td>
</tr>
<tr height="500px">
<td colspan="2" valign="top">${board.content }</td>
</tr>
</table>
</body>
</html>
▶boardEdit
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시글 수정</title>
<style>
h2 {
text-align: center;
}
table {
margin: auto;
}
</style>
</head>
<body>
<h2>게시글 수정</h2>
<form action="/board/edit/${board.id}" , method="post">
<input type="hidden" name="pageNum" value="${pageNum }"> <input
type="hidden" name="pageAmount" value="${pageAmount}">
<table border="1" width="1000px">
<caption>
<strong>* 표시: 수정 가능</strong>
</caption>
<colgroup>
<col width="20%">
<col width="80%">
</colgroup>
<input type="hidden" name="id" id="id" value="${board.id }" />
<tr>
<th>제목 *</th>
<td><input type="text" style="width: 300px; border: none"
name="title" id="title" value="${board.title }" required />
</tr>
<tr>
<th>작성자</th>
<td><strong>${board.writer }</strong>
</tr>
<tr height="300px">
<th>내용*</th>
<td><textarea style="border: none;" rows="40" cols="120"
name="content">${board.content }</textarea>
</tr>
<tr style="border: none">
<td colspan="2" align="right">
<div>
<input type="button" value="목록" onclick="location.href='/board/list?pageNum=${pageNum }&pageAmount=${pageAmount}'">
<input type="reset" value="초기화" />
<input type="submit" value="수정" />
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
▶boardList
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시판 목록</title>
<style>
h1, h2{
text-align: center;
}
table{
margin: auto;
}
</style>
</head>
<body>
<h1>게시판 목록</h1>
<br/>
<h2><c:if test="${pageMaker.searchWord!='' }">"${pageMaker.searchWord }" 검색 결과</c:if></h2>
<table width="930px">
<tr>
<td align="right"><input type="button" value="글 작성" onclick="location.href='/board/regist'">
</tr>
</table>
<table border="1" width="930px">
<tr>
<th width="50px">No</th>
<th width="400px">제목</th>
<th width="80px">작성자</th>
<th width="80px">조회수</th>
<th width="160px">작성일</th>
<th width="160px">수정일</th>
</tr>
<c:forEach var="boardList" items="${boardList }">
<tr>
<td>${boardList.id }</td>
<td><a href="/board/detail/${boardList.id }?searchType=${pageMaker.searchType }&searchWord=${pageMaker.searchWord }&pageNum=${pageMaker.pageNum}&pageAmount=${pageMaker.pageAmount}">${boardList.title }</a></td>
<td>${boardList.writer }</td>
<td>${boardList.views }</td>
<td>${boardList.regist_datetime }</td>
<td>${boardList.modify_datetime }</td>
</tr>
</c:forEach>
</table>
<br/>
<div align="center">
<c:if test="${pageMaker.prev }">
<a href="/board/list?searchType=${pageMaker.searchType }&searchWord=${pageMaker.searchWord }&pageNum=${pageMaker.startPage - 1 }&pageAmount=${pageMaker.pageAmount }"><</a>
</c:if>
<c:forEach var="num" begin="${pageMaker.startPage }" end="${pageMaker.endPage }" step="1">
<c:if test="${num == pageMaker.pageNum }">
<b>${num }</b>
</c:if>
<c:if test="${num != pageMaker.pageNum }">
<a href="/board/list?searchType=${pageMaker.searchType }&searchWord=${pageMaker.searchWord }&pageNum=${num }&pageAmount=${pageMaker.pageAmount}">${num }</a>
</c:if>
</c:forEach>
<c:if test="${pageMaker.next }">
<a href="/board/list?searchType=${pageMaker.searchType }&searchWord=${pageMaker.searchWord }&pageNum=${pageMaker.endPage + 1 }&pageAmount=${pageMaker.pageAmount }">></a>
</c:if>
</div>
<br/>
<form action="/board/list" method="get" style="text-align: center;">
<div>
<select name="searchType">
<option value="" <c:out value="${pageMaker.searchType==''? 'selected':'' }" />>all</option>
<option value="title" <c:out value="${pageMaker.searchType=='title'? 'selected':'' }" />>제목</option>
<option value="content" <c:out value="${pageMaker.searchType=='content'? 'selected':'' }" />>내용</option>
<option value="writer" <c:out value="${pageMaker.searchType=='writer'? 'selected':'' }" />>작성자</option>
<option value="tc" <c:out value="${pageMaker.searchType=='tc'? 'selected':'' }" />>제목+내용</option>
</select>
<input type="text" name="searchWord" value="${pageMaker.searchWord }">
<input type="hidden" name="pageNum" value="${pageMaker.pageNum }">
<input type="hidden" name="pageAmount" value="${pageMaker.pageAmount }">
<input type="submit" value="검색">
</div>
</form>
</body>
</html>
▶boardRegister
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
h2{
text-align: center;
}
table{
margin: auto;
}
</style>
<title>게시글 작성</title>
</head>
<body>
<h2>게시글 작성</h2>
<form action="/board/regist", method = "post">
<table border="1" width="930px">
<caption><strong>* 표시는 필수입력</strong></caption>
<colgroup>
<col width="20%">
<col width="80%">
</colgroup>
<tr>
<th>제목 *</th>
<td><input type="text" style="width:300px;border:none" name="title" id="title" required />
</tr>
<tr>
<th>작성자 *</th>
<td><input type="text" style="width:300px;border:none" name="writer" id="writer" required />
</tr>
<tr height = "300px">
<th>내용</th>
<td><textarea style="border: none;" rows="40" cols="120" name="content"></textarea>
</tr>
</table>
<table width="1000px">
<tr>
<td align="right"><input type="button" value="목록" onclick="location.href='/board/list'">
<input type="reset" value="초기화" />
<input type="submit" value="등록" /></td>
</tr>
</table>
</form>
</body>
</html>
'ETC' 카테고리의 다른 글
Spring + Ajax 중복된 파일 이름 해결 (0) | 2022.09.25 |
---|---|
Spring + Ajax 파일 확장자, 크기 제한 (Ajax) (0) | 2022.09.25 |
Spring + Ajax 파일 업로드 (0) | 2022.09.25 |
[SpringMVC + MyBatis + MySql] 게시판 댓글 수 게시판 List에 출력 (0) | 2022.09.25 |
[SpringMVC + MyBatis + Ajax] 게시판 댓글 추가/삭제/List (Ajax 이용) (0) | 2022.09.24 |