본문 바로가기

Programming/국비학원

221103 - MVC - 글 수정, 삭제

  • 글 수정
  • viewArticle.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<%
	request.setCharacterEncoding("utf-8");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글 상세 보기</title>
<style type="text/css">
	#btn_modify{
		display:none;
	}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
	//돌아가기 버튼
	function backToList(obj){
		obj.action="${contextPath}/board/listArticles.do";
		obj.submit();
	}
	
	////수정하기 버튼 => 제목, 내용, 첨부파일 수정 가능하도록 & 수정 반영 버튼 표시
	function fn_enable(obj){
		document.getElementById("title").disabled=false; 
		document.getElementById("content").disabled=false;
		let imgName=document.getElementById("imageFileName");
		if (imgName!=null){
			imgName.disabled=false;
		}
		document.getElementById("btn_modify").style.display="block";
		document.getElementById("btn_all").style.display="none";
	}
	
	//이미지파일 첨부시 미리보기 기능
	function readURL(input){
		if (input.files && input.files[0]){
			let reader=new FileReader();
			reader.onload=function(event){
				$('#preview').attr('src',event.target.result);
			}
			reader.readAsDataURL(input.files[0]);
		}
	}
	
	////수정 반영 버튼
	function fn_modify(obj){
		obj.action="${contextPath}/board/modArticle.do"
		obj.submit();
	}
</script>
<body>
	<form name="formArticle" action="post" enctype="multipart/form-data">
		<table align="center">
			<tr>
				<td width="150" align="center" bgcolor="beige">글번호</td>
				<td>
					<input type="text" value="${article.articleNo}" disabled>
					<input type="hidden" name="articleNo" value="${article.articleNo}" /> <!--  -->
				</td>
			</tr>
			<tr>
				<td width="150" align="center" bgcolor="beige">아이디</td>
				<td><input type="text" name="id" id="id"
				value="${article.id}" disabled></td>
			</tr>
			<tr>
				<td width="150" align="center" bgcolor="beige">제목</td>
				<td><input type="text" name="title" id="title" value="${article.title}" disabled></td> ////
			</tr>			
			<tr>
				<td width="150" align="center" bgcolor="beige">내용</td>
				<td><textarea name="content" id="content" disabled>${article.content}</textarea></td> ////
			</tr>	
			<c:if test="${not empty article.imageFileName}">
				<tr>
					<td width="150" align="center" bgcolor="beige">이미지</td>
					<td>
						<input type="hidden" name="original" value="${article.imageFileName}">
						<img src="${contextPath}/download.do?articleNo=${article.articleNo}&
						imageFileName=${article.imageFileName}" id=preview><br>
					</td>
				</tr>
				<tr>
					<td>
						<input colspan="2" type="file" name="imageFileName" id="imageFileName"
                        disabled onchange="readURL(this);">  ////
					</td>
				</tr>
			</c:if>
			<tr>
				<td width="150" align="center" bgcolor="beige">등록일자</td>
				<td>
					<input type="text" value="<fmt:formatDate value="${article.writeDate}"/>" disabled>
				</td>
			</tr>
			<tr id="btn_modify">
				<td colspan="2" align="center">
					<input type="button" value="수정 반영" onclick="fn_modify(formArticle)">  ////
					<input type="button" value="리스트로 돌아가기" onclick="backToList(formArticle)">
					
				</td>
			</tr>
			<tr>
				<td id="btn_all">
					<input colspan="2" type="button" value="수정하기" onclick="fn_enable(this.form);"> ////
					<input colspan="2" type="button" value="삭제하기" onclick="">
					<input colspan="2" type="button" value="돌아가기" onclick="backToList(formArticle);">
					<input colspan="2" type="button" value="답글쓰기" onclick="">						
				</td>
			</tr>
		</table>
	</form>
</body>
</html>

 

 

 

  • BoardController
		} else if (action.equals("/modArticle.do")){ //수정 후 반영
			
			Map<String, String> articleMap = upload(request, response);
			
			int articleNo = Integer.parseInt(articleMap.get("articleNo"));
			String title = articleMap.get("title");
			String content = articleMap.get("content");
			String imageFileName = articleMap.get("imageFileName");
			
			
			vo.setArticleNo(articleNo);
			vo.setTitle(title);
			vo.setContent(content);
			vo.setImageFileName(imageFileName);
			
			bs.modArticle(vo);
			
			if (imageFileName != null && imageFileName.length() != 0) {
				
				String original = articleMap.get("original");
				
				File srcfile = new File(ART_IMAGE_REPO+"/temp/"+imageFileName); //파일 객체 생성
				File destDir = new File(ART_IMAGE_REPO+"/"+articleNo); //디렉토리 객체 생성
			
				FileUtils.moveFileToDirectory(srcfile, destDir, true); //새 파일을 dest 디렉토리로 이동
				
				File oldFile = new File(ART_IMAGE_REPO+"/"+articleNo+"/"+original); //기존 이미지 파일 객체 생성
				oldFile.delete(); //삭제
				
			}
			
			PrintWriter pw = response.getWriter();
			pw.print("<script>"
					+ "alert('글을 수정했습니다');"
					+ "location.href='"+request.getContextPath()+"/board/viewArticle.do?articleNo="
					+articleNo+"';"
					+ "</script>");
			return;
			
		}

 

 

 

  • BoardService
	public void modArticle(ArticleVO vo) {
		
		dao.updateArticle(vo);
		
	}

 

 

 

  • BoardDAO
	//글 수정
	public void updateArticle(ArticleVO vo) {
		
		int articleNo=vo.getArticleNo();
		String title=vo.getTitle();
		String content=vo.getContent();
		String imageFileName=vo.getImageFileName();
		
		try {
			con=dataFactory.getConnection();
			String query = "update board_qna set title=?,content=?";
			if (imageFileName != null && imageFileName.length() != 0) {
				query+=", imagefile=?";
			}
			query+=" where articleno=?";
			
			System.out.println(query);
			ps=con.prepareStatement(query);
			ps.setString(1, title);
			ps.setString(2, content);
			if (imageFileName != null && imageFileName.length() != 0) {
				ps.setString(3, imageFileName);
				ps.setInt(4, articleNo);
			} else {
				ps.setInt(3, articleNo);
			}
			ps.executeUpdate();
			
			ps.close();
			con.close();
			
		}catch(Exception e) {
			System.out.println("글 상세 수정 중 에러");
		}
		
	}

 

 

//에러 
http://localhost:8070/jspMVC/board/modArticle.do?title=c&content=f&original=a.PNG&imageFileName=

 

 

 

 

  • 삭제
  • viewArticle.jsp
	//삭제
	function fn_remove(url, articleNo){
		let newForm = document.createElement("form");
		newForm.setAttribute("method","post");
		newForm.setAttribute("action",url);
		
		let articleNoInput=document.createElement("input");
		articleNoInput.setAttribute("type","hidden");
		articleNoInput.setAttribute("name","articleNo");
		articleNoInput.setAttribute("value",articleNo);
		
		newForm.appendChild(articleNoInput);
		document.body.appendChild(newForm);
		newForm.submit();
	}
</script>
~
<input colspan="2" type="button" value="삭제하기" 
onclick="fn_remove('${contextPath}/board/removeArticle.do',${article.articleNo});">

 

 

 

  • BoardController
		} else if (action.equals("/removeArticle.do")){
			
			int articleNo=Integer.parseInt(request.getParameter("articleNo"));
			List<Integer> articleNoList = bs.removeArticle(articleNo); //디렉토리 삭제할 글번호 리스트
			
			for (int ano:articleNoList){ //
				File imgDir = new File(ART_IMAGE_REPO+"/"+ano);
				if (imgDir.exists()) {
					FileUtils.deleteDirectory(imgDir); //디렉토리 삭제
				}
			}
			
			PrintWriter pw = response.getWriter();
			pw.print("<script>"
					+ "alert('글을 삭제했습니다');"
					+ "location.href='"+request.getContextPath()+"/board/listArticles.do';"
					+ "</script>");
			return;
			
			
		}else {
			
			nextPage="/board/listArticles.jsp";
			
		}

 

 

 

  • BoardService 
	public List<Integer> removeArticle(int articleNo){
		List<Integer> articleNoList=dao.selectRemoveArticles(articleNo); //디렉토리 삭제할 글번호 모음
		dao.deleteArticle(articleNo); //관련 게시글들 삭제
		return articleNoList;
	}

 

 

 

  • BoardDAO
	//디렉토리 삭제할 글번호 리스트
	public List<Integer> selectRemoveArticles(int articleNo){
		
		List<Integer> articleNoList = new ArrayList<Integer>();
		
		try {
			con=dataFactory.getConnection();
			String query = "select articleno from board_qna start with articleno=?"
					+ " connect by prior articleno=parentno"; //prior: 
			System.out.println(query);
			
			ps=con.prepareStatement(query);
			ps.setInt(1, articleNo);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				articleNo=rs.getInt("articleno");
				articleNoList.add(articleNo);
			}
			
			ps.close();
			con.close();
		} catch (Exception e) {
			System.out.println("삭제할 글 번호 리스트 처리 중 에러");
		}
		
		return articleNoList;
		
	}
	
	//글 삭제 (자식글 포함)
	public void deleteArticle(int articleNo) {
		try {
			
			con=dataFactory.getConnection();
			String query = "delete from board_qna where articleno in "
					+ "(select articleno from board_qna"
					+ " start with articleno=?"
					+ " connect by prior articleno=parentno)"; 
			System.out.println(query);
			
			ps=con.prepareStatement(query);
			ps.setInt(1, articleNo);
			ps.executeUpdate();
		
			ps.close();
			con.close();
			
		} catch (Exception e) {
			
			System.out.println("삭제 처리 중 에러");
			
		}
	}