Java/Spring

Spring 기초(scheduler) - AWS 풀스택 과정 70일차

awspspgh 2024. 11. 4. 18:08
목차
1. file
2. scheduler
3. cmtQty & hasFile

 

1. file

BoardController.java

package com.ezen.spring.controller;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ezen.spring.domain.BoardDTO;
import com.ezen.spring.domain.BoardVO;
import com.ezen.spring.domain.FileVO;
import com.ezen.spring.domain.PagingVO;
import com.ezen.spring.handler.FileHandler;
import com.ezen.spring.handler.PagingHandler;
import com.ezen.spring.service.BoardService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
@RequestMapping("/board/*")
@Controller
public class BoardController {
	// 생성자 주입시 객체는 final로 생성
	private final BoardService bsv;
	private final FileHandler fh;
	
	// return void => 온 경로 그대로 리턴 /board/register => /board/register.jsp
	@GetMapping("/register")
	public void register() {}
	
	// 첨부파일 => multipartFile / 여러 개... multipartFile[]
	@PostMapping("/insert")
	public String insert(BoardVO bvo, MultipartFile[] files) {
		log.info(">>> insert bvo > {}", bvo);
		List<FileVO> flist = null;

		if(files[0].getSize() > 0) {
			// 파일의 내용이 있다면
			flist = fh.uploadFiles(files);
			log.info(">>>>> flist > {}", flist);
		}
			
		// files 정보를 이용하여 => List<FileVO> 변환을 하는 핸들러
		// fileHandler => return List<FileVO> + 파일 저장
		
		BoardDTO bdto = new BoardDTO(bvo, flist); // bvo.flist 
//		int isOk = bsv.insert(bvo);
		int isOk = bsv.insert(bdto);
		log.info(">>> insert > {}", isOk > 0 ? "OK" : "FAIL");
		// /WEB-INF/views/.jsp (x)
		// 컨트롤러의 mapping 위치로 연결할 때 redirect:/board/list
		return "redirect:/";
	}
	
	@GetMapping("/list")
	public String list(Model m, PagingVO pgvo) {
		// request.setAttrbute()
		// Model 객체가 해당 일을 대신해줌.
//		PagingVO pgvo = new PagingVO();
		List<BoardVO> list = bsv.getList(pgvo);
		// totalcount 구해서 PagingHandler에 매개변수로 전달
		int totalCount = bsv.getTotal(pgvo);
		PagingHandler ph = new PagingHandler(totalCount, pgvo);
		log.info(">>> totalCount > {}", totalCount);
		m.addAttribute("list",list);
		m.addAttribute("ph",ph);
		return "/board/list";
	}
	
	@PostMapping("/update")
	public String update(BoardVO bvo, @RequestParam(name="files", required = false) MultipartFile[] files) {
		List<FileVO> flist = null;
		
		if(files[0].getSize() > 0) {
			flist = fh.uploadFiles(files);
		}		
		int isOk = bsv.modify(new BoardDTO(bvo, flist));
//		int isOk = bsv.modify(bvo);
		log.info(">>> update > {}", isOk > 0 ? "OK" : "FAIL");
		
		// detail.jsp로 이동 X => controller detail mapping으로 이동 => redirect:/
		return "redirect:/board/detail?bno="+bvo.getBno();
	}
	
	// @ requestParam("bno") int bno => 전달되는 파라미터가 여러 개일 경우 이름을 명시
	// return void : 요청 경로로 응답을 그대로 보냄. /board/detail => /board/detail.jsp
	@GetMapping({"/detail", "/modify"})
	public void detail(int bno, Model m) {
		// bno에 해당하는 BoardVO 객체를 DB에서 가져와서 모델로 전달
//		BoardVO bvo = bsv.getDetail(bno);
//		m.addAttribute("bvo", bvo)
		BoardDTO bdto = bsv.getDetail(bno);
		m.addAttribute("bdto", bdto);
//		return "/board/detail";
	}
	
	@GetMapping("/delete")
	public String delete(int bno) {
		int isOk = bsv.delete(bno);
		log.info(">>> delete > {}", isOk > 0 ? "OK" : "FAIL");
		return "redirect:/board/list";
	}
	
	@ResponseBody
	@DeleteMapping("/file/{uuid}")
	public String fileDelete(@PathVariable("uuid")String uuid) {
		int isOk = bsv.removeFile(uuid);
		return isOk > 0 ? "1":"0";
	}
	
}

 

 BoardService.java

package com.ezen.spring.service;

import java.util.List;

import com.ezen.spring.domain.BoardDTO;
import com.ezen.spring.domain.BoardVO;
import com.ezen.spring.domain.FileVO;
import com.ezen.spring.domain.PagingVO;

public interface BoardService {

//	int insert(BoardVO bvo);

	List<BoardVO> getList(PagingVO pgvo);

	BoardDTO getDetail(int bno);

//	int modify(BoardVO bvo);

	int delete(int bno);

	int getTotal(PagingVO pgvo);

	int insert(BoardDTO bdto);

	int removeFile(String uuid);

	int modify(BoardDTO boardDTO);

}

 

 BoardServiceImpl.java

package com.ezen.spring.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ezen.spring.dao.BoardDAO;
import com.ezen.spring.dao.FileDAO;
import com.ezen.spring.domain.BoardDTO;
import com.ezen.spring.domain.BoardVO;
import com.ezen.spring.domain.FileVO;
import com.ezen.spring.domain.PagingVO;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@RequiredArgsConstructor
@Slf4j
@Service
public class BoardServiceImpl implements BoardService{
	private final BoardDAO bdao;
	private final FileDAO fdao;

//	@Override
//	public int insert(BoardVO bvo) {
//		// TODO Auto-generated method stub
//		return bdao.insert(bvo);
//	}

	@Override
	public List<BoardVO> getList(PagingVO pgvo) {
		// TODO Auto-generated method stub
		return bdao.getList(pgvo);
	}

//	@Override
//	public BoardVO getDetail(int bno) {
//		// TODO Auto-generated method stub
//		bdao.updateReadCount(bno);
//		return bdao.getDetail(bno);
//	}

//	@Override
//	public int modify(BoardVO bvo) {
//		// TODO Auto-generated method stub
//		return bdao.update(bvo);
//	}

	@Override
	public int delete(int bno) {
		// TODO Auto-generated method stub
		return bdao.delete(bno);
	}

	@Override
	public int getTotal(PagingVO pgvo) {
		// TODO Auto-generated method stub
		return bdao.getTotal(pgvo);
	}
	
	@Transactional
	@Override
	public int insert(BoardDTO bdto) {
		// bvo + file
		// bno 먼저 insert 하고 난 후 bno를 DB에서 빼와야 함. > fvo를 DB에 저장
		int isOk = bdao.insert(bdto.getBvo());
		if(bdto.getFlist() == null) { // 첨부파일이 없을 경우
			return isOk;	
		}
		
		// 첨부파일이 있는 케이스
		if(isOk > 0 && bdto.getFlist().size() > 0) {
			// bno setting
			long bno = bdao.getOneBno(); // 가장 마지막에 등록된 bno
			for(FileVO fvo : bdto.getFlist()) {
				fvo.setBno(bno);
				isOk *= fdao.insertFile(fvo);
			}
		}
		return isOk;
	}

	@Transactional
	@Override
	public BoardDTO getDetail(int bno) {
		// bdao > bvo / fdao > fvo 묶어서 BoardDTO로 리턴
		bdao.updateReadCount(bno);
		BoardVO bvo = bdao.getDetail(bno);
		List<FileVO> flist = fdao.getList(bno);
		
		BoardDTO bdto = new BoardDTO(bvo, flist);
		return bdto;
	}

	@Override
	public int removeFile(String uuid) {
		// TODO Auto-generated method stub
		return fdao.removeFile(uuid);
	}

	@Transactional
	@Override
	public int modify(BoardDTO boardDTO) {
		// TODO Auto-generated method stub
		int isOk = bdao.update(boardDTO.getBvo());
		if(boardDTO.getFlist() == null) {
			return isOk;
		}
		if(isOk > 0 && boardDTO.getFlist().size()>0) {
			for(FileVO fvo : boardDTO.getFlist()) {
				fvo.setBno(boardDTO.getBvo().getBno());
				isOk *= fdao.insertFile(fvo);
			}
		}
		return isOk;
	}

}

 

 register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c "%>


<div class="container-md">
<jsp:include page="../layout/header.jsp"/>
<hr>
<!-- enctype : multipart/form-data -->
<form action="/board/insert" method="post" enctype="multipart/form-data">
<div class="mb-3">
  <label for="t" class="form-label">title</label>
  <input type="text" class="form-control" id="t" name="title" placeholder="title...">
</div>
<div class="mb-3">
  <label for="w" class="form-label">writer</label>
  <input type="text" class="form-control" id="w" name="writer" placeholder="writer...">
</div>
<div class="mb-3">
  <label for="c" class="form-label">content</label>
  <textarea class="form-control" id="c" rows="3" name="content" ></textarea>
</div>
	<!-- 첨부파일 입력 라인 추가 -->
	<div class="mb-3">
	  <label for="file" class="form-label"></label>
	  <input type="file" class="form-control" id="file" name="files" multiple="multiple" style="display:none;">
	  <button type="button" class="btn btn-info" id="trigger">FileUpload...</button>
	</div>
	<!-- 첨부파일 표시 라인 추가 -->
	<div class="mb-3" id="fileZone">
	
	</div>
<button type="submit" class="btn btn-primary" id="regBtn">register</button>
</form>
</div>

<script type="text/javascript" src="/resources/js/boardRegister.js"></script>

<jsp:include page="../layout/footer.jsp"/>

</body>
</html>

 

 detail.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<jsp:include page="../layout/header.jsp"/>
<body>
<div class="container-md">
	<h1>Board Detail Page...</h1>
	
	<!-- request 객체로 온 값은 ${bdto} -->
	<!-- c:set은 값을 저장하는 용도 -->
	<c:set value= "${bdto.bvo}" var="bvo"></c:set>
	
	<div class="mb-3">
		  <label for="t" class="form-label">title</label>
		  <input type="text" class="form-control" id="t" value="${bvo.title}" readonly>
		</div>
		<div class="mb-3">
		  <label for="w" class="form-label">writer</label>
		  <input type="text" class="form-control" id="w" value="${bvo.writer}" readonly>
		  <span class="bodge text-bg-Info">${bvo.regDate}</span>
		</div>
		<div class="mb-3">
		  <label for="c" class="form-label">content</label>
		  <textarea class="form-control" id="c" rows="3" readonly>${bvo.content}</textarea>
		</div>
		
		<!-- file upload 표시라인 -->
		<c:set value="${bdto.flist}" var="flist"></c:set>
		<div class="mb-3">
			<ul class="list-group list-group-flush">
				<!-- 파일의 개수만큼 li를 반복하여 파일 표시 타입이 1인경우만 그림을 표시 -->
				<c:forEach items="${flist }" var="fvo">
					<li class="list-group-item">
						<c:choose>
							<c:when test="${fvo.fileType > 0}">
								<div>
									<img alt="" src="/upload/${fvo.saveDir}/${fvo.uuid}_th_${fvo.fileName}">
								</div>
							</c:when>
							<c:otherwise>
								<!-- 일반 파일 : 아이콘 하나 가져와서 다운로드 가능하게 생성 -->
								<a href="/upload/${fvo.saveDir}/${fvo.uuid}_th_${fvo.fileName}" download = "${fvo.fileName }">
									<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-file-earmark-arrow-down-fill" viewBox="0 0 16 16">
									  <path d="M9.293 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4.707A1 1 0 0 0 13.707 4L10 .293A1 1 0 0 0 9.293 0M9.5 3.5v-2l3 3h-2a1 1 0 0 1-1-1m-1 4v3.793l1.146-1.147a.5.5 0 0 1 .708.708l-2 2a.5.5 0 0 1-.708 0l-2-2a.5.5 0 0 1 .708-.708L7.5 11.293V7.5a.5.5 0 0 1 1 0"/>
									</svg>
								</a>
							</c:otherwise>
						</c:choose>
						<div class="fw-bold">${fvo.fileName }</div>
						<span class="badge text-bg-primary rounded-pill">${fvo.regDate } / ${fvo.fileSize }Bytes</span>
					</li>
				</c:forEach>
			</ul>
		</div>
		
		<a href="/board/modify?bno=${bvo.bno }"><button type="button" class="btn btn-success">modify</button></a>
		<a href="/board/delete?bno=${bvo.bno }"><button type="button" class="btn btn-danger">delete</button></a>
		
		<!-- comment line -->
		<!-- comment post -->
		<div class="input-group mb-3">
		  <span class="input-group-text" id="cmtWriter">tester1@tester.com</span>
		  <input type="text" id="cmtText" class="form-control" placeholder="Add Comment" aria-label="Username" aria-describedby="basic-addon1">
		  <button type="button" id="cmtAddBtn" class="btn btn-success">post</button>
		</div>
		<br>
		<hr>
		<!-- comment  print-->
		<ul class="list-group list-group-flush" id="cmtListArea">
		  <li class="list-group-item">
		   <div class="me-2 me-auto">
		      <div class="fw-bold">writer</div>
		      Content
		    </div>
		    <span class="badge text-bg-primary rounded-pill">regDate</span>
		  </li>
		</ul>
		
		<!-- 댓글 더보기 버튼 : 더 표시하고자 하는 댓글이 없으면 사라지게함. -->
		<div>
		  <button type="button" id="moreBtn" data-page="1" class="btn btn-dark" style="visibility:hidden">More +</button>
		</div>
		
		<!-- model line -->
		<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
		  <div class="modal-dialog">
		    <div class="modal-content">
		      <div class="modal-header">
		        <h1 class="modal-title fs-5" id="cmtWriterMod">Writer</h1>
		        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
		      </div>
		      <div class="modal-body">
		        <input type="text" id="cmtTextMod" class="form-control">
		      </div>
		      <div class="modal-footer">
		        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
		        <button type="button" id="cmtModBtn" class="btn btn-primary">changes</button>
		      </div>
		    </div>
		  </div>
		</div>
		
		<script type="text/javascript">
		let bnoVal = `<c:out value="${bvo.bno}" />`;
		console.log(bnoVal);
		</script>
		
		<script type="text/javascript" src="/resources/js/boardDetailComment.js"></script>
		
		<script type="text/javascript">
			spreadCommendList(bnoVal);
		</script>
		
	</div>
</body>
<jsp:include page="../layout/footer.jsp"/>

 

 modify.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<jsp:include page="../layout/header.jsp"/>
<body>
<div class="container-md">
	<h1>Board Modify Page...</h1>
	<c:set value= "${bdto.bvo}" var="bvo"></c:set>
	<form action="/board/update" method="post" enctype="multipart/form-data">
	<div class="mb-3">
	  <label for="n" class="form-label">no.</label>
	  <input type="hidden" name="bno" value="${bvo.bno }">
	  <input type="text" class="form-control" id="n" value="${bvo.bno}" readonly>
	</div>
	<div class="mb-3">
	  <label for="t" class="form-label">title</label>
	  <input type="text" class="form-control" id="t" name="title" value="${bvo.title}">
	</div>
	<div class="mb-3">
	  <label for="w" class="form-label">writer</label>
	  <input type="text" class="form-control" id="w" value="${bvo.writer}" readonly>
	  <span class="bodge text-bg-Info">${bvo.regDate}</span>
	</div>
	<div class="mb-3">
	  <label for="c" class="form-label">content</label>
	  <textarea class="form-control" id="c" rows="3" name="content">${bvo.content}</textarea>
	</div>
	
	<!-- file 추가 -->
	<!-- 첨부파일 입력 라인 추가 -->
	<div class="mb-3">
	  <label for="file" class="form-label"></label>
	  <input type="file" class="form-control" id="file" name="files" multiple="multiple" style="display:none;">
	  <button type="button" class="btn btn-info" id="trigger">FileUpload...</button>
	</div>
	<!-- 첨부파일 표시 라인 추가 -->
	<div class="mb-3" id="fileZone">
	
	</div>
	
	<!-- file -->
	<c:set value="${bdto.flist}" var="flist"></c:set>
		<div class="mb-3">
			<ul class="list-group list-group-flush">
				<!-- 파일의 개수만큼 li를 반복하여 파일 표시 타입이 1인경우만 그림을 표시 -->
				<c:forEach items="${flist }" var="fvo">
					<li class="list-group-item">
						<c:choose>
							<c:when test="${fvo.fileType > 0}">
								<div>
									<img alt="" src="/upload/${fvo.saveDir}/${fvo.uuid}_th_${fvo.fileName}">
								</div>
							</c:when>
							<c:otherwise>
								<!-- 일반 파일 : 아이콘 하나 가져와서 다운로드 가능하게 생성 -->
								<a href="/upload/${fvo.saveDir}/${fvo.uuid}_th_${fvo.fileName}" download = "${fvo.fileName }">
									<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-file-earmark-arrow-down-fill" viewBox="0 0 16 16">
									  <path d="M9.293 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4.707A1 1 0 0 0 13.707 4L10 .293A1 1 0 0 0 9.293 0M9.5 3.5v-2l3 3h-2a1 1 0 0 1-1-1m-1 4v3.793l1.146-1.147a.5.5 0 0 1 .708.708l-2 2a.5.5 0 0 1-.708 0l-2-2a.5.5 0 0 1 .708-.708L7.5 11.293V7.5a.5.5 0 0 1 1 0"/>
									</svg>
								</a>
							</c:otherwise>
						</c:choose>
						<div class="fw-bold">${fvo.fileName }</div>
						<span class="badge text-bg-primary rounded-pill">${fvo.regDate } / ${fvo.fileSize }Bytes</span>
						<button type="button" data-uuid="${fvo.uuid }" class="btn btn-outline-danger btn-sm file-x">x</button>
					</li>
				</c:forEach>
			</ul>
		</div>
		<button type="submit" class="btn btn-success" id="regBtn">modify</button>
		<a href="/board/list"><button type="button" class="btn btn-danger">list</button></a>
	</form>
	<script type="text/javascript" src="/resources/js/boardModify.js"></script>
	<script type="text/javascript" src="/resources/js/boardRegister.js"></script>
	</div>
</body>
<jsp:include page="../layout/footer.jsp"/>

 

 boardModify.js

- VSCode와 연동 (연동 이후 node와 연결을 허락하지 말 것!! 허락할 시 재앙을 맛봄)

/**
 * 
 */
console.log("boardModify.js in")
document.addEventListener('click', (e)=> {
    if(e.target.classList.contains('file-x')){
        let uuid = e.target.dataset.uuid;
        removeFileToServer(uuid).then(result =>{
            if(result == '1'){
                e.target.closest('li').remove();
            }
        })
    }
})

async function removeFileToServer(uuid) {
    try{
        const url = '/board/file/'+uuid;
        const config={
            method:'delete'
        }
        const resp = await fetch(url, config);
        const result = await resp.text();
        return result;
    }  catch (error){
        console.log(error);
    }
}

 

▷ 출력

파일 수정 및 삭제

 

파일 다운로드

 

2. scheduler

 FileSweeper.java

package com.ezen.spring.handler;

import java.io.File;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.ezen.spring.dao.FileDAO;
import com.ezen.spring.domain.FileVO;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
@Component
@EnableScheduling
public class FileSweeper {
	// 직접 DB 접속을 해서 처리
	private final FileDAO fdao;
	
	private final String BASE_PATH="D:\\_myProject\\_java\\_fileUpload\\";
	
	// 매일 정해진 시간에 스케줄려를 실행
	// 매일 등록된 파일과 (DB) <-> 해당 일자의 폴더에 있는 파일이 일치하는 파일은 남기고.
	// 일치하지 않는 파일이 있다면 삭제 (DB에는 없는데, 폴더에는 남아있는 파일이 있다면 삭제)
	// file.delete() - fileRemoveHandler를 사용하여 삭제해도 무방함.
	
	// 스케쥴 기록 cron 방식 초 분 시 일 월 요일 년도(생략가능)
	// (cron="59 59 23 * * *") : 매일 23시59분59초에 실행
	@Scheduled(cron="00 15 13 * * *")
	public void fileSweeper() {
		log.info(">>>>> FileSweeper Running Start~!! : {}", LocalDateTime.now());
		// 처리
		
		// db에 등록된 모든 파일 목록을 가져오기
		List<FileVO> dbList = fdao.selectListAllFile();
		
		// D:\_myProject\_java\_fileUpload\2024\11\04\\uuid_파일명
		// D:\_myProject\_java\_fileUpload\2024\11\04\\uuid_th_파일명 => 이미지만 존재
		// 파일경로+파일명을 붙인 (실제 존재해야 하는 파일리스트)
		List<String> currFiles = new ArrayList<String>();
		for(FileVO fvo : dbList) {
			String filePath = fvo.getSaveDir()+File.separator+fvo.getUuid();
			String fileName = fvo.getFileName();
			currFiles.add(BASE_PATH+filePath+"_"+fileName);
			
			// 이미지라면 썸네일 경로도 추가 = 이미지 파일은 1로 줌
			if(fvo.getFileType() > 0) {
				currFiles.add(BASE_PATH+filePath+"_th_"+fileName);
			}
		}
		log.info(">>>>> currFiles >> {}", currFiles);
		
		// 실제 파일 경로를 설정
		LocalDate now = LocalDate.now();
		String today = now.toString();
		today = today.replace("-", File.separator);
		
		// 경로를 기반으로 저장되어있는 파일을 검색
		// D:\_myProject\_java\_fileUpload\2024\11\04
		File dir = Paths.get(BASE_PATH+today).toFile();
		// listFiles() : 경로안에 있는 모든 파일을 배열로 리턴
		File[] allFileObject = dir.listFiles();
		log.info(">>>>> all file Object >>> {}", allFileObject.toString());
		
		// 실제 저장되어있는 파일목록과, DB의 존재 파일을 비교하여 DB에 없는 파일은 삭제 진행
		for(File file : allFileObject) {
			String storedFileName = file.toPath().toString();
			if(!currFiles.contains(storedFileName)) {
				file.delete(); // 파일 삭제
				log.info(">>>>> delete files >>> {}", storedFileName);
			}
		}
		
		log.info(">>>>> FileSweeper Running End~!! : {}", LocalDateTime.now());
	}
}

 

 FileDAO.java

package com.ezen.spring.dao;

import java.util.List;

import com.ezen.spring.domain.FileVO;

public interface FileDAO {

	int insertFile(FileVO fvo);

	List<FileVO> getList(int bno);

	int removeFile(String uuid);

	List<FileVO> selectListAllFile();

}

 

 fileMapper.xml

<?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="com.ezen.spring.dao.FileDAO">
  	<insert id="insertFile">
  		insert into file(uuid, save_dir, file_name, file_type, bno, file_size) values(#{uuid}, #{saveDir}, #{fileName}, #{fileType}, #{bno}, #{fileSize})
  	</insert>
  	<select id="getList" resultType="com.ezen.spring.domain.FileVO">
  		select * from file where bno = #{bno}
  	</select>
  	 <delete id="removeFile">
  		delete from file where uuid = #{uuid}
  	</delete>
  	<select id="selectListAllFile" resultType="com.ezen.spring.domain.FileVO">
  		select * from file
  	</select>
  </mapper>

 

 ServletConfiguration.java

package com.ezen.spring.config;

import org.springframework.context.annotation.Bean;

//import javax.servlet.MultipartConfigElement;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@EnableScheduling
@EnableWebMvc
@ComponentScan(basePackages = {"com.ezen.spring.controller","com.ezen.spring.service","com.ezen.spring.handler"})
public class ServletConfiguration implements WebMvcConfigurer{

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// resources 경로 설정 (css, js, img, font)
		registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
		// 나중에 파일 업로드 경로도 추가 예정
		registry.addResourceHandler("/upload/**").addResourceLocations("file:///D:\\_myProject\\_java\\_fileUpload\\");
	}

	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		// view를 jsp(jstl 포함)로 어떻게 보여줄지 설정
		// view 경로 설정
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setPrefix("/WEB-INF/views/");
		viewResolver.setSuffix(".jsp");
		// 화면에 뷰를 구성할 때 jstl에 대한 사용을 하는 jsp를 구성하겠다.
		viewResolver.setViewClass(JstlView.class);
		
		registry.viewResolver(viewResolver);
	}

	// 나중에 파일 업로드 리졸버도 추가 예정.
	// 빈 이름이 multipartResolver이어야 에러가 안 남
	@Bean(name = "multipartResolver")
	public MultipartResolver getMultipartResolver( ) {
		StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
		return multipartResolver;
	}
}

 

pom.xml

스케줄러 관련 디펜던시
quartz 2.3.2 / quarts-jobs 2.3.2

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.ezen</groupId>
	<artifactId>spring</artifactId>
	<name>spring_study_javaClass</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>11</java-version>
		<org.springframework-version>5.3.10</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>2.0.7</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<!-- logback-classic 1.4.5 / logback-core / log4jdbc-log4j2-jdbc4.1-1.16 -->
		<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
		<dependency>
		    <groupId>ch.qos.logback</groupId>
		    <artifactId>logback-classic</artifactId>
		    <version>1.4.5</version>
		    <!-- <scope>test</scope> -->
		</dependency>
		<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-core -->
		<dependency>
		    <groupId>ch.qos.logback</groupId>
		    <artifactId>logback-core</artifactId>
		    <version>1.4.5</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.bgee.log4jdbc-log4j2/log4jdbc-log4j2-jdbc4.1 -->
		<dependency>
		    <groupId>org.bgee.log4jdbc-log4j2</groupId>
		    <artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
		    <version>1.16</version>
		</dependency>
	

		<!-- <dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency> -->

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>
		
		<!-- 여기서부터 추가 dependency -->
		<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
		<dependency>
		    <groupId>org.projectlombok</groupId>
		    <artifactId>lombok</artifactId>
		    <version>1.18.34</version>
		    <scope>provided</scope>
		</dependency>
		<!-- DB 관련 -->
		<!-- mysql-connector-j-8.0.33 / mybatis-3.5.10 / mybatis-spring-2.0.6 -->        
        <!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
		<dependency>
		    <groupId>com.mysql</groupId>
		    <artifactId>mysql-connector-j</artifactId>
		    <version>8.0.33</version>
		</dependency>
		<!-- spring-JDBC-5.3.10 / spring-Test-5.3.10 -->
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-jdbc</artifactId>
		    <version>${org.springframework-version}</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-test</artifactId>
		    <version>${org.springframework-version}</version>
		    <scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.5.10</version>
		</dependency>
		 <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-spring</artifactId>
		    <version>2.0.6</version>
		</dependency>
		
		<!-- Hikari CP -->
		<dependency>
		   <groupId>com.zaxxer</groupId>
		   <artifactId>HikariCP</artifactId>
		   <version>6.0.0</version>
		</dependency>
		
		<!-- 댓글관련 : json 파싱 역할 -->
		<!-- jackson-databind-2.13.0 jackson-dataformat-xml -->
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
		<dependency>
		    <groupId>com.fasterxml.jackson.core</groupId>
		    <artifactId>jackson-databind</artifactId>
		    <version>2.13.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml -->
		<dependency>
		    <groupId>com.fasterxml.jackson.dataformat</groupId>
		    <artifactId>jackson-dataformat-xml</artifactId>
		    <version>2.13.1</version>
		</dependency>
		
		<!-- 파일관련 -->
		<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
		<dependency>
		    <groupId>commons-io</groupId>
		    <artifactId>commons-io</artifactId>
		    <version>2.11.0</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
		<dependency>
		    <groupId>commons-fileupload</groupId>
		    <artifactId>commons-fileupload</artifactId>
		    <version>1.4</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
		<dependency>
		    <groupId>net.coobird</groupId>
		    <artifactId>thumbnailator</artifactId>
		    <version>0.4.14</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.tika/tika-core -->
		<dependency>
		    <groupId>org.apache.tika</groupId>
		    <artifactId>tika-core</artifactId>
		    <version>2.4.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.tika/tika-parsers -->
		<dependency>
		    <groupId>org.apache.tika</groupId>
		    <artifactId>tika-parsers</artifactId>
		    <version>2.4.1</version>
		    <type>pom</type>
		    
		    
		    
		</dependency>
		<!-- 스케쥴러 관련 -->
		    <!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
		<dependency>
		    <groupId>org.quartz-scheduler</groupId>
		    <artifactId>quartz</artifactId>
		    <version>2.3.2</version>
		</dependency>
		    
		    <!-- 시큐리티 관련 -->
		    <!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz-jobs -->
		<dependency>
		    <groupId>org.quartz-scheduler</groupId>
		    <artifactId>quartz-jobs</artifactId>
		    <version>2.3.2</version>
		</dependency>

	</dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
            <!-- 플러그인 추가 : web.xml이 없어도 class를 통해서 설정정보를 읽을 수 있게 추가 설정-->
            <plugin>
            	<groupId>org.apache.maven.plugins</groupId>
            	<artifactId>maven-war-plugin</artifactId>
            	<version>3.4.0</version>
            	<configuration>
            		<failOnMissingWebXml>false</failOnMissingWebXml>
            	</configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

▷ 출력

=> DB와 폴더에 있는 파일이름을 비교하여 DB에 없는 파일을 폴더에서 삭제함 (file delete - DB와 폴더의 일관성)

 

3. cmtQty & hasFile

 BoardVO.java

package com.ezen.spring.domain;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class BoardVO {
//	bno bigint auto_increment,
//	title varchar(500) not null,
//	writer varchar(500) not null,
//	content text,
//	is_del varchar(5) default 'N',
//	reg_date datetime default now(),
//	read_cout int default 0,
	
	private long bno;
	private String title;
	private String writer;
	private String content;
	private String isDel;
	private String regDate;
	private int readCount;
	private int cmtQty;
	private int hasFile;
}

 

 BoardServiceImpl.java

package com.ezen.spring.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ezen.spring.dao.BoardDAO;
import com.ezen.spring.dao.FileDAO;
import com.ezen.spring.domain.BoardDTO;
import com.ezen.spring.domain.BoardVO;
import com.ezen.spring.domain.FileVO;
import com.ezen.spring.domain.PagingVO;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@RequiredArgsConstructor
@Slf4j
@Service
public class BoardServiceImpl implements BoardService{
	private final BoardDAO bdao;
	private final FileDAO fdao;

//	@Override
//	public int insert(BoardVO bvo) {
//		// TODO Auto-generated method stub
//		return bdao.insert(bvo);
//	}
		
	@Override
	public List<BoardVO> getList(PagingVO pgvo) {
		// TODO Auto-generated method stub
		bdao.updateCmtQty();
		bdao.updateHasFile();
		return bdao.getList(pgvo);
	}

//	@Override
//	public BoardVO getDetail(int bno) {
//		// TODO Auto-generated method stub
//		bdao.updateReadCount(bno);
//		return bdao.getDetail(bno);
//	}

//	@Override
//	public int modify(BoardVO bvo) {
//		// TODO Auto-generated method stub
//		return bdao.update(bvo);
//	}

	@Override
	public int delete(int bno) {
		// TODO Auto-generated method stub
		return bdao.delete(bno);
	}

	@Override
	public int getTotal(PagingVO pgvo) {
		// TODO Auto-generated method stub
		return bdao.getTotal(pgvo);
	}
	
	@Transactional
	@Override
	public int insert(BoardDTO bdto) {
		// bvo + file
		// bno 먼저 insert 하고 난 후 bno를 DB에서 빼와야 함. > fvo를 DB에 저장
		int isOk = bdao.insert(bdto.getBvo());
		if(bdto.getFlist() == null) { // 첨부파일이 없을 경우
			return isOk;	
		}
		
		// 첨부파일이 있는 케이스
		if(isOk > 0 && bdto.getFlist().size() > 0) {
			// bno setting
			long bno = bdao.getOneBno(); // 가장 마지막에 등록된 bno
			for(FileVO fvo : bdto.getFlist()) {
				fvo.setBno(bno);
				isOk *= fdao.insertFile(fvo);
			}
		}
		return isOk;
	}

	@Transactional
	@Override
	public BoardDTO getDetail(int bno) {
		// bdao > bvo / fdao > fvo 묶어서 BoardDTO로 리턴
		bdao.updateReadCount(bno);
		BoardVO bvo = bdao.getDetail(bno);
		List<FileVO> flist = fdao.getList(bno);
		
		BoardDTO bdto = new BoardDTO(bvo, flist);
		return bdto;
	}

	@Override
	public int removeFile(String uuid) {
		// TODO Auto-generated method stub
		return fdao.removeFile(uuid);
	}

	@Transactional
	@Override
	public int modify(BoardDTO boardDTO) {
		// TODO Auto-generated method stub
		int isOk = bdao.update(boardDTO.getBvo());
		if(boardDTO.getFlist() == null) {
			return isOk;
		}
		if(isOk > 0 && boardDTO.getFlist().size()>0) {
			for(FileVO fvo : boardDTO.getFlist()) {
				fvo.setBno(boardDTO.getBvo().getBno());
				isOk *= fdao.insertFile(fvo);
			}
		}
		return isOk;
	}

}

 

 BoardDAO.java

package com.ezen.spring.dao;

import java.util.List;

import com.ezen.spring.domain.BoardVO;
import com.ezen.spring.domain.PagingVO;

public interface BoardDAO {

	int insert(BoardVO bvo);

	List<BoardVO> getList(PagingVO pgvo);

	BoardVO getDetail(int bno);

	int update(BoardVO bvo);

	int delete(int bno);

	int getTotal(PagingVO pgvo);

	void updateReadCount(int bno);

	long getOneBno();

	void updateCmtQty();

	void updateHasFile();
}

 

 boardMapper.xml

<?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">
  
  <!-- DAOImpl() 없음. => namespace="다오인터페이스명" id="메서드명" -->
  <mapper namespace="com.ezen.spring.dao.BoardDAO">
  	<insert id="insert">
  		insert into board(title, writer, content)
  		values(#{title}, #{writer}, #{content})
  	</insert>
  	<select id="getList" resultType="com.ezen.spring.domain.BoardVO">
  		select * from board where is_del = 'N' 
  		<include refid="search"></include>
  		order by bno desc limit #{pageStart}, #{qty}
  	</select>
  	<select id="getDetail" resultType="com.ezen.spring.domain.BoardVO">
  		select * from board where bno = #{bno}
  	</select>
  	<update id="update">
  		update board set title = #{title}, content = #{content} where bno = #{bno}
  	</update>
  	<update id="delete">
  		update board set is_del = 'Y' where bno = #{bno}
  	</update>
  	<select id="getTotal" resultType="int">
  		select count(bno) from board where is_del = 'N'
  		<include refid="search"></include>
  	</select>
  	<update id="updateReadCount">
  		update board set read_count = read_count + 1 where bno = #{bno}
  	</update>
  	<select id="getOneBno" resultType="long">
  		select max(bno) from board
  	</select>
  	<update id="updateCmtQty">
  		update board b set cmt_qty = (select count(bno) from comment where bno = b.bno);
  	</update>
  	<update id="updateHasFile">
  		update board b set has_file = (select count(bno) from file where bno = b.bno);
  	</update>
  	<!-- search 동적 쿼리 -->
  	<!-- 
	  	select * from board 
	  	where is_del = 'N' and title like concat('%', keyword, '%') or writer like concat('%', keyword, '%') )
	  	order by bno desc 
	  	limit #{pageStart}, #{qty} 
  	-->
  	
  	<sql id="search">
  		<if test="type!=null">
  			<trim prefix="and(" suffix=")" suffixOverrides="or">
  				<foreach collection="typeToArray" item="type">
  					<trim suffix="or">
  						<choose>
  							<when test="type == 't'.toString()">
  								title like concat('%', #{keyword}, '%')
  							</when>
  							<when test="type == 'w'.toString()">
  								writer like concat('%', #{keyword}, '%')
  							</when>
  							<when test="type == 'c'.toString()">
  								content like concat('%', #{keyword}, '%')
  							</when>
  						</choose>
  					</trim>
  				</foreach>
  			</trim>
  		</if>
  	</sql>
  	
  </mapper>

 

 list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<jsp:include page="../layout/header.jsp"/>
<div class="container-md">
<h1>Board List Page...</h1>
<hr>
<!-- search line -->
<div class="container-fluid">
 	<form action="/board/list" method="get" class="d-flex" role="search">
 	<select class="form-select" name="type" id="inputGroupSelect01">
	    <option ${ph.pgvo.type == null ? 'selected' : '' }>Choose...</option>
	    <option value="t" ${ph.pgvo.type eq 't' ? 'selected' : '' }>title</option>
	    <option value="w" ${ph.pgvo.type eq 'w' ? 'selected' : '' }>writer</option>
	    <option value="c" ${ph.pgvo.type eq 'c' ? 'selected' : '' }>content</option>
	    <option value="tw" ${ph.pgvo.type eq 'tw' ? 'selected' : '' }>title + writer</option>
	    <option value="wc" ${ph.pgvo.type eq 'wc' ? 'selected' : '' }>writer + content</option>
	    <option value="tc" ${ph.pgvo.type eq 'tc' ? 'selected' : '' }>content + title</option>
	    <option value="twc">all</option>
 	</select>
       <input class="form-control me-2" name="keyword" type="search" placeholder="Search" value="${ph.pgvo.keyword}" aria-label="Search">
       <input type="hidden" name="pageNo" value="1">
       <input type="hidden" name="qty" value="${ph.pgvo.qty }">
      <button type="submit" class="btn btn-primary position-relative">
		  search
		  <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
		    ${ph.totalCount }
		  </span>
	</button>
     </form>
     <%-- ${ph } --%>
</div>

<table class="table table-hover">
 <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">title</th>
      <th scope="col">writer</th>
      <th scope="col">regDate</th>
      <th scope="col">readCount</th>
      <th scope="col">
      	<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-file-earmark-arrow-down-fill" viewBox="0 0 16 16">
			<path d="M9.293 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4.707A1 1 0 0 0 13.707 4L10 .293A1 1 0 0 0 9.293 0M9.5 3.5v-2l3 3h-2a1 1 0 0 1-1-1m-1 4v3.793l1.146-1.147a.5.5 0 0 1 .708.708l-2 2a.5.5 0 0 1-.708 0l-2-2a.5.5 0 0 1 .708-.708L7.5 11.293V7.5a.5.5 0 0 1 1 0"/>
		</svg>
	</th>
    </tr>
  </thead>
  <tbody>
  <c:forEach items="${list}" var="bvo">
  	<tr>
	  	<td>${bvo.bno }</td>
	  	<td>
	  		<a href="/board/detail?bno=${bvo.bno }">${bvo.title }</a>
	  			<c:if test="${bvo.cmtQty > 0 }">
	  				<span class="fw-bold text-danger">[${bvo.cmtQty }]</span>
	  			</c:if>
	  	</td>
	  	<td>${bvo.writer }</td>
	  	<td>${bvo.regDate }</td>
	  	<td>${bvo.readCount }</td>
	  	<td>${bvo.hasFile }</td>
  	</tr>
  	</c:forEach>
  </tbody>
</table>

<!-- pagination line -->
<!-- << >> : 값이 false disabled -->
<nav aria-label="Page navigation example">
  <ul class="pagination justify-content-center">
    <li class="page-item ${ph.prev eq false ? 'disabled' : ''}">
      <a class="page-link" href="/board/list?pageNo=${ph.startPage-1 }&qty=${ph.pgvo.qty}&type=${ph.pgvo.type}&keyword=${ph.pgvo.keyword}" aria-label="Previous">
        <span aria-hidden="true">&laquo;</span>
      </a>
    </li>
    <c:forEach begin="${ph.startPage }" end="${ph.endPage }" var="i">
    <li class="page-item ${ph.pgvo.pageNo eq i ? 'active' : ''}"><a class="page-link" href="/board/list?pageNo=${i }&qty=${ph.pgvo.qty}&type=${ph.pgvo.type}&keyword=${ph.pgvo.keyword}">${i }</a></li>
    </c:forEach>
   <!--  <li class="page-item"><a class="page-link" href="#">2</a></li>
    <li class="page-item"><a class="page-link" href="#">3</a></li> -->
    <li class="page-item ${ph.next eq false ? 'disabled' : ''}" >
      <a class="page-link" href="/board/list?pageNo=${ph.endPage+1}&qty=${ph.pgvo.qty}&type=${ph.pgvo.type}&keyword=${ph.pgvo.keyword}" aria-label="Next">
        <span aria-hidden="true">&raquo;</span>
      </a>
    </li>
  </ul>
</nav>

<a href="/"><button type="submit" class="btn btn-success">list</button></a>

</div>
<jsp:include page="../layout/footer.jsp"/>

 

▷ 출력

댓글 수 & 첨부파일 수

 

출처 : https://blog.naver.com/momonocha/223645924413