CRUD식으로 코드들의 순서를 바꾸면서 구조도 바꾸었다! 훨씬 깔끔하고 해당 기능들을 찾기 편해졌다ㅎㅎㅎ
코드도 정리를 잘해야 협업할 때 확실이 편한 것 같다.
각설하고 관리자 페이지에서 게시판을 전체 조회할 때 각각의 게시판마다 게시글이 몇개 있는지 출력하도록 기능을 추가 했다!
이때 고민한게 있는데
1. 관리자 페이지를 조회할 때마다 DB 에서 게시글 수를 긁어와서 보여줄까
2. 게시글을 쓰고 지울 때마다 각 게시판의 게시글 개수를 +1 -1을 해줄까 였다
여쭤보니 결론은 --조회보단 업데이트 빈도수가 적으니까 업데이트로 ==> 게시글을 작성/ 삭제할 때마다 +1 or -1 하는 걸로!
각각 BoardService, BoardServiceImple, BoardDao-mapper, Controller 에 다음 코드를 추가 해주었다
Boardcontroller.java 중 일부
// 게시글 삭제
@GetMapping("/post/delete/{postNo}")
public String delete(@PathVariable("postNo") int postNo, HttpServletRequest request) {
// 작성자 본인이거나 관리자 인지 권한 확인
// 세션 준비
HttpSession session = request.getSession();
MemberVo member = (MemberVo) session.getAttribute("member");
// 회원이 아닌 경우 작성이 제한됨
if (member == null) {
//회원이 아닌 경우 로그인 페이지로 이동함
return "redirect:/login?redirectUrl=/post/" + postNo;
} else {
// 회원 id
int memNo = member.getMemNo();
// 작성된 게시글 작성자 id
PostVo post = this.postService.retrieveDetailBoard(postNo);
int writerNo = post.getWriterNo();
System.out.println("회원" + memNo + "작성자" + writerNo);
// 작성자 본인이 아닌 경우
if (memNo != writerNo) {
//권한 없음 페이지로 이동
return "redirect:/denine";
} else {
// 작성자 본인인 경우
// 해당 게시글의 board pk값 받아옴 (삭제 후 목록이로 이동하기 위함)
int boardNo = post.getBoardNo();
// 삭제 쿼리 실행
this.postService.removePost(postNo);
//게시글 삭제시 총 개수 수정 boardNo
//게시글 등록은 filecontroller에 있음
boardService.reviseBoardPost(boardNo, -1);
return "redirect:/board/" + boardNo;
}
}
}
맨 밑의 주석달린 삭제시 게시글의 총개수 수정 부분을 보면 된다. 그리고 게시글 개수를 내가 담당하게 되어 게시판 관련 코드에 포함되어있다. 필요해서 찾아볼 때 주의!
--FileController.java의 일부
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String registerFiles(HttpServletRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images,
@RequestParam(value = "videos", required = false) List<MultipartFile> videos,
@RequestParam(value = "bordNo", required = false, defaultValue = "1") int boardNo,
@RequestParam(value = "subject", required = false) String subject,
@RequestParam(value = "content", required = false) String content,
@RequestParam(value = "tag", required = false) String tag,
@RequestParam(value = "roomNo", required = false, defaultValue = "-1") int roomNo,
@RequestParam(value = "rateLoc", required = false) int rateLoc,
@RequestParam(value = "rateClean", required = false) int rateClean,
@RequestParam(value = "rateComu", required = false) int rateComu,
@RequestParam(value = "rateChip", required = false) int rateChip,
@RequestParam(value = "visitDate", required = false) String visitDate,
@RequestParam(value = "recommendPlace", required = false) String recommendPlace,
@RequestParam(value = "notRecommendPerson", required = false) String notRecommendPerson) {
int writerNo = 1;
HttpSession session = request.getSession();
try {
MemberVo memberVo = (MemberVo) session.getAttribute("member");
writerNo = memberVo.getMemNo();
} catch (Exception e) {
}
String newContent = convert(content);
PostVo postVo = new PostVo();
postVo.setWriterNo(writerNo);
postVo.setBoardNo(boardNo);
postVo.setSubject(subject);
postVo.setContent(newContent);
postVo.setTag(tag);
int postNo = postService.registerPost(postVo);
session.setAttribute("boardNo", boardNo);
if (roomNo != -1) {
ReviewVo review = new ReviewVo();
review.setRoomNo(roomNo);
review.setRateLoc(rateLoc);
review.setRateClean(rateClean);
review.setRateComu(rateComu);
review.setRateChip(rateChip);
review.setVisitDate(visitDate);
review.setRecommendPlace(recommendPlace);
review.setNotRecommendPerson(notRecommendPerson);
this.reviewService.registerReview(review);
}
if (images != null) {
System.out.println("images");
for (MultipartFile file : images) {
String fileName = null;
if (!file.getOriginalFilename().isEmpty()) {
fileName = fileUploadService.restore(file, postNo, 1);
} else {
fileName = "default.jpg";
}
}
}
if (videos != null) {
System.out.println("videos");
for (MultipartFile file : videos) {
String fileName = null;
if (!file.getOriginalFilename().isEmpty()) {
fileName = fileUploadService.restore(file, postNo, 2);
} else {
fileName = "default.mp4";
}
}
}
//게시글 등록시 총 개수 수정 boardNo
boardService.reviseBoardPost(boardNo, 1);
return "redirect:/post/" + postVo.getPostNo();
}
여기에서 맨 밑의 주석부분// 게시글 등록시 총 개수 수정 부분을 보면 된다.
--추가한 부분들 --
BoardDao.java 의 일부
//게시판 게시글 수 수정(증가 감소)
int updateBoardPost(int boardNo, int updatepostCount);
BoardService.java의 일부
//게시판 게시글 갯수 수정
int reviseBoardPost(int boardNo, int postCount);
BoardServiceImpl.java의 일부
// 게시판 게시글 갯수 수정을 위한 조회
@Override
public int reviseBoardPost(int boardNo, int postCount) {
return this.boardDao.updateBoardPost(boardNo, postCount);
}
BoardDao-mapper.xml
<!-- 게시판 게시글 수 수정 -->
<update id="updateBoardPost" >
UPDATE board
SET bo_post = bo_post + #{updatepostCount}
WHERE bo_no = #{boardNo}
</update>
쿼리문을 짜는 것도 어렵다ㅠㅠ 이렇게 각각 코드를 추가함으로 써 백단의 기능추가는 완료했다
====================================================================
프론트부분
board_list.html 전문
<!DOCTYPE html>
<html layout:decorate="~{layout/admin_layout}" xmlns="http://www.w3.org/1999/xhtml"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:th="http://www.thymeleaf.org">
<div layout:fragment="page-title">게시판 관리</div>
<div layout:fragment="content">
<div class="card shadow mb-4">
<div class="card-body">
<div class="table-responsive">
<div class="dataTables_wrapper dt-bootstrap4" id="dataTable_wrapper">
<div class="row text-right">
<div class="col-sm-12">
<a class="btn btn-primary" style="float: right" th:href="@{/intranet/board/write}">게시판
등록</a>
</div>
</div>
<form id="boardList">
<div class="row">
<div class="col-sm-12">
<table aria-describedby="dataTable_info" cellspacing="0"
class="table table-bordered dataTable"
id="dataTable" role="grid" style="width: 100%;"
width="100%">
<thead>
<tr role="row">
<th>#</th>
<th>게시판ID</th>
<th>게시판 명</th>
<th>게시판 그룹</th>
<th>접근등급</th>
<th>게시판 유형</th>
<th>게시글 갯수</th>
<th>비고</th>
</tr>
</thead>
<tbody>
<tr th:each="board : ${boardList}">
<td>
<span th:text="${boardStat.count}"></span>
</td>
<td th:text="${board.boardNo}"></td>
<td>
<a th:href="@{/intranet/board/}+${board.boardNo}">
<span th:text="${board.title}"></span>
</a>
</td>
<td th:text="${board.groupName}"></td>
<td th:text="${board.boGrade}"></td>
<td th:text="${board.type}"></td>
<td th:text="${board.postCount}"></td>
<td>
<a class="btn btn-primary btn-sm moveBtn"
th:href="@{/board/}+${board.boardNo}"
type="button">게시판이동 </a>
<button class="btn btn-primary btn-sm delectBtn" type="button">삭제
</button>
<input class="boardNo" name="boardNo" th:value="${board.boardNo}"
type="hidden">
</td>
</tr>
</tbody>
</table>
</div>
<script>
$(function () {
$(".delectBtn").on('click', function () {
if (confirm("해당 게시판을 정말 삭제하시겠습니까?")) {
let boardNo = $(this).next(".boardNo").val();
$.ajax({
url : '/intranet/board_delete/' + boardNo,
type : 'GET',
success: function (data) {
if (data == "success") {
location.reload();
} else {
alert("올바르게 작동하지 않았습니다.");
return false;
}
},
error : function (err) {
console.log(err);
}
});
}
;
});
});
</script>
</div>
</form>
<div class="row">
<div class="col-sm-12">
<div class="dataTables_paginate paging_simple_numbers" id="dataTable_paginate">
<th:block layout:fragment="paging" th:include="@{/fragment/pagination}"></th:block>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
요기서 중간에 보면 ${board.postCount}가 보일거다 게시글 개수를 뽑아다가 보여준다!
---최종화면
'Spring boot > 3차 프로젝트 중 알게 된 것!' 카테고리의 다른 글
[3차 프로젝트]게시판 또는 게시판 그룹 별 게시판/게시글 개수 세서 프론트에 보내주기 (0) | 2022.01.10 |
---|---|
[3차 프로젝트] 2022-01-03일자 에로사항....Error updating database. Cause: java.sql.SQLIntegrityConstraintViolationException: (0) | 2022.01.07 |
[3차 프로젝트] Intellij import가 제대로 안되거나 잘 돌아가던게 갑자기 빨간 줄이 생길 때 해결 법 (0) | 2022.01.07 |
[3차 프로젝트 ] @ResponseBody과 mapping에 대해 간단한 정리 (0) | 2022.01.07 |
[3차 프로젝트]Ajax로 DB에 있는 게시판 목록 끌어오기 (0) | 2022.01.07 |