Java/Spring

Spring 기초(file) - AWS 풀스택 과정 69일차

awspspgh 2024. 11. 1. 18:16
목차
1. comment
2. file

 

1. comment

- D드라이브에 파일 생성

 

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

 

▣ BoardServiceImpl.java

package com.ezen.spring.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.ezen.spring.dao.BoardDAO;
import com.ezen.spring.domain.BoardVO;
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;

	@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);
	}
}

 

▣ 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);

}

 

▣ 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>
  	<!-- 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>

 

▣ 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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ezen.spring.domain.BoardVO;
import com.ezen.spring.domain.PagingVO;
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;
	
	// return void => 온 경로 그대로 리턴 /board/register => /board/register.jsp
	@GetMapping("/register")
	public void register() {}
	
	@PostMapping("/insert")
	public String insert(BoardVO bvo) {
		log.info(">>> insert bvo > {}", bvo);
		int isOk = bsv.insert(bvo);
		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) {
		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);
//		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";
	}
	
	
}

 

▣ CommentController.java

package com.ezen.spring.controller;

//import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.ezen.spring.domain.CommentVO;
import com.ezen.spring.domain.PagingVO;
import com.ezen.spring.handler.PagingHandler;
import com.ezen.spring.service.CommentService;

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

@RequiredArgsConstructor
@Slf4j
@RequestMapping("/comment/*")
@RestController
public class CommentController {

	private final CommentService csv;
	
	@PostMapping("/post")
	public ResponseEntity<String> post(@RequestBody CommentVO cvo) {
		log.info(">>>> post cvo > {}", cvo);
		int isOk = csv.post(cvo);
		return isOk > 0 ?
				new ResponseEntity<String>("1",HttpStatus.OK) :
				new ResponseEntity<String>("0", HttpStatus.INTERNAL_SERVER_ERROR); //error
	}
	
//	@GetMapping(value="/{bno}/{page}", produces = MediaType.APPLICATION_JSON_VALUE)
//	public ResponseEntity<List<CommentVO>> list(@PathVariable("bno") long bno){
//		List<CommentVO> list = csv.getList(bno);
//		return new ResponseEntity<List<CommentVO>>(list, HttpStatus.OK);
//	}
	
	@GetMapping(value="/{bno}/{page}", produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<PagingHandler> list(@PathVariable("bno") long bno, @PathVariable("page") int page){
		PagingVO pgvo = new PagingVO(page, 5); // DB에 전달할 값을 설정 limit 0, 5
		PagingHandler ph = csv.getList(bno, pgvo); // 화면에 더보기 버튼의 표시유무
		return new ResponseEntity<PagingHandler>(ph, HttpStatus.OK);
	}
	
//	@PutMapping("/modify")
//	public ResponseEntity<String> update(@RequestBody CommentVO cvo){
//		
//	}
	
	@ResponseBody
	@PutMapping("/modify")
	public String modify(@RequestBody CommentVO cvo) {
		int isOk = csv.modify(cvo);
		return isOk > 0 ? "1" : "0";
	}
	
	@ResponseBody
	@DeleteMapping("/{cno}")
	public String delete(@PathVariable("cno") long cno) {
		int isOk = csv.delete(cno);
		return isOk > 0 ? "1" : "0";		
	}
	
}

 

▣ CommentService.java

package com.ezen.spring.service;

//import java.util.List;

import com.ezen.spring.domain.CommentVO;
import com.ezen.spring.domain.PagingVO;
import com.ezen.spring.handler.PagingHandler;

public interface CommentService {

	int post(CommentVO cvo);

//	List<CommentVO> getList(long bno);

	int modify(CommentVO cvo);

	int delete(long cno);

	PagingHandler getList(long bno, PagingVO pgvo);

}

 

▣ CommentServiceImpl.java

package com.ezen.spring.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.ezen.spring.dao.CommentDAO;
import com.ezen.spring.domain.CommentVO;
import com.ezen.spring.domain.PagingVO;
import com.ezen.spring.handler.PagingHandler;

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

@RequiredArgsConstructor
@Slf4j
@Service
public class CommentServiceImpl implements CommentService{

	private final CommentDAO cdao;

	@Override
	public int post(CommentVO cvo) {
		// TODO Auto-generated method stub
		return cdao.post(cvo);
	}

//	@Override
//	public List<CommentVO> getList(long bno) {
//		// TODO Auto-generated method stub
//		return cdao.getList(bno);
//	}

	@Override
	public int modify(CommentVO cvo) {
		// TODO Auto-generated method stub
		return cdao.modify(cvo);
	}

	@Override
	public int delete(long cno) {
		// TODO Auto-generated method stub
		return cdao.delete(cno);
	}

	@Override
	public PagingHandler getList(long bno, PagingVO pgvo) {
		// ph 객체 안에 cmtList / totalCount 구해오기
		List<CommentVO> cmtList = cdao.getList(bno, pgvo);
		int totalCount = cdao.getTotalCount(bno);
		PagingHandler ph = new PagingHandler(totalCount, pgvo, cmtList);
		return ph;
	}
}

 

▣ CommentDAO.java

package com.ezen.spring.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

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

public interface CommentDAO {

	int post(CommentVO cvo);

//	List<CommentVO> getList(long bno);

	int modify(CommentVO cvo);

	int delete(long cno);

	List<CommentVO> getList(@Param("bno") long bno, @Param("pgvo") PagingVO pgvo);

	int getTotalCount(long bno);

}

 

▣ commentMapper.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.CommentDAO">
  	<insert id="post">
  		insert into comment(bno, writer, content) values(#{bno}, #{writer}, #{content})
  	</insert>
  	<!-- <select id="getList" resultType="com.ezen.spring.domain.CommentVO">
  		select * from comment where bno = #{bno} order by cno desc
  	</select> -->
  	<select id="getList" resultType="com.ezen.spring.domain.CommentVO">
  		select * from comment where bno = #{bno} order by cno desc limit #{pgvo.pageStart}, #{pgvo.qty}
  	</select>
  	<select id="getTotalCount" resultType="int">
  		select count(cno) from comment where bno = #{bno}
  	</select>
  	<update id="modify">
  		update comment set content = #{content}, reg_date = now() where cno = #{cno}
  	</update>
  	<delete id="delete">
  		delete from comment where cno = #{cno} 
  	</delete>
  </mapper>

 

▣ boardDetailComment.js

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

/**
 * 
 */
 
 console.log("boardDetailComment.js in");

 console.log("vscode 연동 성공");

 document.getElementById('cmtAddBtn').addEventListener('click', ()=>{
    const cmtText = document.getElementById('cmtText');
    const cmtWriter = document.getElementById('cmtWriter');

    if(cmtText.value == null || cmtText.value == ''){
        alert('댓글을 입력해주세요.');
        cmtText.focus();
        return false;
    }
    let cmtData = {
        bno: bnoVal,
        writer: cmtWriter.innerText,
        content: cmtText.value
    }
    console.log(cmtData);
    postCommentToServer(cmtData).then(result => {
        if(result == '1'){
            alert("댓글 등록 성공");
            cmtText.value="";
            // 댓글 뿌리기
            spreadCommendList(bnoVal);
        }
    })
 });

 function spreadCommendList(bno, page=1){
    getCommentListFromServer(bno, page).then(result =>{
        console.log("ph>", result);
        // 댓글 뿌리기
        const ul = document.getElementById('cmtListArea');
        if(result.cmtList.length > 0){
            if(page == 1){
                ul.innerHTML = ""; // 반복 전에 기존 샘플 버리기 (더보기 버튼에 의한 누적 불가능)
            }
            for(let cvo of result.cmtList){
                let li = `<li class="list-group-item" data-cno=${cvo.cno}>`;
                li += `<div class="me-2 me-auto">`;
                li += `<div class="fw-bold">${cvo.writer}</div>`;
                li += `${cvo.content} </div>`;
                li += `<span class="badge text-bg-primary rounded-pill">${cvo.regDate}</span>`;
                // 수정 삭제 버튼 추가
                li += `<button type="button" data-cno=${cvo.cno} class="btn btn-outline-warning btn-sm mod" data-bs-toggle="modal" data-bs-target="#myModal">%</button>`;
                li += `<button type="button" data-cno=${cvo.cno} class="btn btn-outline-danger btn-sm del">X</button>`;
                li += `</li>`;
                ul.innerHTML += li;
            }
            // 더보기 버튼 숨김여부 체크 코드
            let moreBtn = document.getElementById('moreBtn');
            // 더보기 버튼이 표시되는 조건
            // result = ph > pgvo > pageNo = 1 / realEndPage = 2
            // 현재 페이지가 전체 페이지보다 작으면 표시
            if(result.pgvo.pageNo < result.realEndPage){
                // style.visiblity = "hidden" : 숨김 / 'visible' : 표시
                moreBtn.style.visibility = 'visible'; // 버튼 표시
                moreBtn.dataset.page = page + 1; // 1 페이지 증가
            } else{
                // 현재 페이지가 전체보다 작지 않다면.. 같거나 크다면...
                moreBtn.style.visibility = 'hidden'; // 숨김
            }

        }else{
            ul.innerHTML = `<div>Comment List Empty</div>`;
            }
        })
    }

    // 수정 삭제
    document.addEventListener('click', (e) => {
        // console.log(e.target);
        // 내가 클릭한 버튼의 객체를 모달창으로 전달
        if(e.target.classList.contains('mod')){
            // 내가 클릭한 버튼의 li 가져오기
            // closest : 가장 가까운(나를 포함한) 태그 (부모태그)
            let li = e.target.closest('li');
            // nextSibling : 한 부모 안에서의 다음 형제 값 찾기
            let cmtText = li.querySelector('.fw-bold').nextSibling;
            console.log(cmtText);
            document.getElementById('cmtTextMod').value = cmtText.nodeValue;
            let cno = li.dataset.cno;
            let cmtWriter = li.querySelector('.fw-bold').innerText;
            document.getElementById('cmtWriterMod').innerText = `no.${cno} <b>${cmtWriter}</b>`;
            // cmtModBtn => cno 값을 dataset으로 달기
            document.getElementById('cmtModBtn').setAttribute("data-cno", cno);
        }
        if(e.target.id == 'cmtModBtn'){
            let cmtData = {
                cno : e.target.dataset.cno,
                content : document.getElementById('cmtTextMod').value
            };
            console.log(cmtData);
            updateCommentToServer(cmtData).then(result =>{
                if(result == '1'){
                    alert("댓글 수정 성공");
                }else{
                    alert("댓글 수정 실패");
                }
                    // 모달창 닫기 : btn-close라는 객체를 클릭해라
                    document.querySelector('.btn-close').click();
                    // 댓글 뿌리기
                    spreadCommendList(bnoVal);
            })

        }
        if(e.target.classList.contains('del')){
            // cno만 있으면 됨.
            let li = e.target.closest('li');
            let cno = li.dataset.cno;
            removeCommentToServer(cno).then(result => {
                if(result == '1'){
                    alert("댓글 삭제 성공");
                }else{
                    alert("댓글 삭제 실패");
                }
                // 댓글 뿌리기
                spreadCommendList(bnoVal);
            })
        }
        if(e.target.id == 'moreBtn'){
            let page = parseInt(e.target.dataset.page);
            spreadCommendList(bnoVal, page);
        }
    })

 async function updateCommentToServer(cmtData) {
    try{
        const url = "/comment/modify";
        const config={
            method: 'put',
            headers:{
                'Content-Type':'application/json; charset=utf-8'
            },
            body: JSON.stringify(cmtData)
        };
        const resp = await fetch(url, config);
        const result = await resp.text(); // isOk
        return result;
    } catch (error){
        console.log(error);
    }
 }

 // delete 메서드 사용
 async function removeCommentToServer(cno) {
    try{
        const url = "/comment/"+cno;
        const config = {
            method : 'delete'
        }
        const resp = await fetch(url, config);
        // const resp = await fetch("/comment/"+cno, {method : 'delete'});
        const result = await resp.text(); // isOk
        return result;
    } catch(error) {
        console.log(error);
    }
 }

 // get은 생략가능.
 async function getCommentListFromServer(bno, page) {
    try{
        const resp = await fetch("/comment/"+bno+"/"+page);
        const result = await resp.json();
        return result;
    } catch (error){
        console.log(error);
    }
 }

 async function postCommentToServer(cmtData) {
    try{
        const url = "/comment/post";
        const config = {
            method: "post",
            headers:{
                'Content-Type':'application/json; charset=utf-8'
            },
            body: JSON.stringify(cmtData)
        };
        const resp = await fetch(url, config);
        console.log(resp);
        const result = await resp.text(); // isOk
        return result;
    } catch(error){
        console.log(error);
    }
 }

 

▣ detial.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>
	<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>
		
		<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"/>

 

▷ 출력

comment more

 

2. file

▣ WebConfig.java

package com.ezen.spring.config;

import javax.servlet.Filter;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer{

	@Override
	protected Class<?>[] getRootConfigClasses() {
		// TODO Auto-generated method stub
		return new Class[] {RootConfig.class};
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		// TODO Auto-generated method stub
		return new Class[] {ServletConfiguration.class};
	}

	@Override
	protected String[] getServletMappings() {
		// TODO Auto-generated method stub
		return new String[] {"/"};
	}

	// encoding filter 설정
	@Override
	protected Filter[] getServletFilters() {
		// TODO Auto-generated method stub
//		CharacterEncodingFilter encoding = new CharacterEncodingFilter("UTF-8", true);
		CharacterEncodingFilter encoding = new CharacterEncodingFilter();
		encoding.setEncoding("UTF-8");
		encoding.setForceEncoding(true); // 외부로 나가는 데이터 인코딩 여부
		
		return new Filter[] {encoding};
	}

	// 사용자 지정 설정이 필요한 경우 사용. (파일업로드)
	@Override
	protected void customizeRegistration(Dynamic registration) {
		// 파일 업로드 설정 (위치 설정)
		String uploadLocation = "D:\\_myProject\\_java\\_fileUpload";
		int maxFileSize = 1024*1024*20; // 20MB
		int maxReqSize = maxFileSize * 3;
		int fileSizeThreshold = maxFileSize;
		
		MultipartConfigElement multipartConfig = new MultipartConfigElement(uploadLocation, maxFileSize, maxReqSize, fileSizeThreshold);
		
		registration.setMultipartConfig(multipartConfig);
	}	
	
}

 

▣ 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.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;

@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;
	}
}

 

▣ FileVO.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 FileVO {
	
	private String uuid;
	private String saveDir;
	private String fileName;
	private int fileType;
	private long bno;
	private long fileSize;
	private String regDate;
	
}

 

▣ 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>
								<!-- 일반 파일 : 아이콘 하나 가져와서 다운로드 가능하게 생성 -->
							</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"/>

 

▣ 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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
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) {
		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";
	}
	
	
}

 

▣ BoardDTO.java

package com.ezen.spring.domain;

import java.util.List;

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

@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class BoardDTO {
	
	private BoardVO bvo;
	private List<FileVO> flist;
}

 

▣ FileHandler.java

package com.ezen.spring.handler;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.tika.Tika;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.ezen.spring.domain.FileVO;

import lombok.extern.slf4j.Slf4j;
//import net.coobird.thumbnailator.Thumbnailator;
import net.coobird.thumbnailator.Thumbnails;

@Slf4j
@Component // 사용자 클래스를 빈으로 등록하는 이노테이션
public class FileHandler {
	
	// 저장 경로
	private final String UP_DIR = "D:\\_myProject\\_java\\_fileUpload";
	
	// 첨부파일을 주고, FileVO의 리스트로 변환하여 리턴 + 저장
	public List<FileVO> uploadFiles(MultipartFile[] files) {
		
		List<FileVO> flist = new ArrayList<>();
		// FileVO 생성 + 파일 저장 + 썸네일 저장
		// 날짜별로 폴더 생성하여 업로드 파일 관리
		LocalDate date = LocalDate.now(); // 오늘날짜 리턴 2024-11-01
		log.info(">> date >>", date.toString());
		String today = date.toString();
		today = today.replace("-", File.separator); // 2024\11\01 win(\) mac(/)
		
		// D:\\_myProject\\_java\\_fileUpload\\2024\\11\\01
		File folders = new File(UP_DIR, today);
		
		// 폴더 생성(있으면 생성 안 함) : mkdir (1개만 생성) mkdirs(하위폴더까지 생성)
		if(!folders.exists()) {
			folders.mkdirs();
		}
		
		// files를 가지고 flist 생성
		for(MultipartFile file : files) {
			FileVO fvo = new FileVO();
			fvo.setSaveDir(today); // 2024\\11\\01
			fvo.setFileSize(file.getSize());
//			String fileName = file.getOriginalFilename();
//			log.info("fileName {}", fileName);
			// 경로를 포함하는 이름이라면...
			String fileName = file.getOriginalFilename().substring(
					file.getOriginalFilename().lastIndexOf(File.separator)+1);
			log.info("fileName {}", fileName);
			fvo.setFileName(fileName);
			
			UUID uuid = UUID.randomUUID();
			String uuidStr = uuid.toString();
			fvo.setUuid(uuidStr);
			
			// ---- fvo 생성 > bno / file_type(File 객체로 전달해야 해서 저장 후 확인)
			// 디스크에 저장 => 저장할 객체(File)를 생성 > 저장
			String fullFileName = uuidStr+"_"+fileName;
			File storeFile = new File(folders, fullFileName);
			
			try {
				file.transferTo(storeFile); // 저장
				// 썸네일 저장 => 이미지만 가능
				// 이미지인지 확인
				if(isImageFile(storeFile)) {
					fvo.setFileType(1); // 이미지 파일만 1
					// 썸네일 생성
					File thumbNail = new File(folders, uuidStr + "_th_" + fileName);
					Thumbnails.of(storeFile).size(100, 100).toFile(thumbNail);
				}
			} catch (Exception e) {
				log.info("파일 저장 오류");
				e.printStackTrace();
			}
			
			// for문 안에 있어야함.
			flist.add(fvo);
			
		}
		
		return flist;
	}
	
	private boolean isImageFile(File storeFile) throws IOException {
		String mimeType = new Tika().detect(storeFile); // "file의 내부요소 type "image/jpeg"
		return mimeType.startsWith("image") ? true : false;
	}
	
}

 

▣ 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.PagingVO;

public interface BoardService {

//	int insert(BoardVO bvo);

	List<BoardVO> getList(PagingVO pgvo);

	BoardVO getDetail(int bno);

	int modify(BoardVO bvo);

	int delete(int bno);

	int getTotal(PagingVO pgvo);

	int insert(BoardDTO bdto);

}

 

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;
	}
}

 

▣ 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();

}

 

▣ 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>
  	
  	<!-- 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>

 

▣ 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);

}

 

▣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>
  </mapper>

 

▣ boardRegister.js

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

/**
 * 
 */
console.log("boardRegister.js in");

// 트리거 버튼 처리
document.getElementById('trigger').addEventListener('click', () => {
    document.getElementById('file').click();
});

// 실행파일에 대한 정규표현식 작성 / 파일 최대 사이즈 20MB
const regExp = new RegExp("\.(exe|jar|msi|dll|sh|bat)$");
const maxSize = 1024*1024*20;

function fileValidation(fileName, fileSize){
    if(regExp.test(fileName)){
        return 0;
    }else if(fileSize > maxSize){
        return 0;
    }else {
        return 1;
    }
}

document.addEventListener('change', (e)=>{
    console.log(e.target);
    if(e.target.id == 'file'){ // 파일창에 변화가 생겼다면..
        // type = 'file' element에 저장된 file 정보를 가져오는 property files
        const fileObj = document.getElementById('file').files;
        console.log(fileObj);
        // 한 번 disabled되면 혼자 false가 될 수 없음. 버튼을 원상복구
        document.getElementById('regBtn').disabled = false;
        // 내가 등록한 파일 정보를 파일 목록으로 기록
        // 등록한 파일이 fileValidation에 맞지 않으면 register 버튼을 비활성화
        // 파일 목록에 업로드 불가능이라고 빨간색 폰트 추가
        let div = document.getElementById('fileZone');
        div.innerHTML = ""; // 새로 추가되는 목록이 있다면 삭제하고 처리

        // ul > li
        /*
        <ul class="list-group">
            <li class="list-group-item">An item</li>
        </ul> 
        */
        // 여러 개의 첨부파일이 모두 검증을 통과해야만 register 버튼을 활성화
        // isOk = 1 * 1 * 1 * 1 => 모두 1 (누적 곱)
        let isOk = 1;
        let ul = `<ul class="list-group list-group-flush">`;
            // 개별 파일에 대한 검증 / 결과 표시
            for(let file of fileObj){
                // 개별 파일에 대한 검증 결과 리턴 변수
                let vaildResult = fileValidation(file.name, file.size);
                isOk *= vaildResult;
                ul += `<li class="list-group-item">`;
                ul += `<div class="me-2 me-auto">`;
                ul += `${vaildResult ? '<div class="fw-bold text-success-emphasis">업로드 가능</div>' : '<div class="fw-bold text-danger-emphasis">업로드 불가능</div>'}`;
                ul += `${file.name}</div>`;
                ul += `<span class="badge text-bg-${vaildResult ? 'success' : 'danger'} rounded-pill">${file.size}</span>`;
                ul += `</li>`;
            }
        ul += `</ul>`
        div.innerHTML = ul;

        if(isOk == 0){
            // 하나라도 검증을 통과하지 못한 파일이 있다면.. 버튼 비활성화
            document.getElementById('regBtn').disabled = true;
        }
        /*
            li += `<div class="me-2 me-auto">`;
            li += `<div class="fw-bold">${cvo.writer}</div>`;
            li += `${cvo.content} </div>`;
            li += `<span class="badge text-bg-primary rounded-pill">${cvo.regDate}</span>`;
        */
    }
});

 

▣ pom.xml

- 디펜던시 추가
commons-fileupload 1.4 / commons-io 2.11.0 / thumbnailator 0.4.14
tika-core 2.4.1 / tika-parsers 2.4.1 : 첨부파일이 이미지 파일인지 확인

<?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>
		
		<!--시큐리티관련, 스케쥴러관련 -->
		
		
		        
	</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>

 

▷ 출력

이미지 등록

 

이미지 디테일