본문 바로가기

웹개발 수업/Server

[Day +87 / Server]내용 추가하세요

211027 수

 

1. 삭제하기

1) galleryDetailView
-<button onclick="location.href='${contextPath}/gallery/list'">목록으로</button>
-<button onclick="deleteBoard();">삭제하기</button>
-<c:if test="${ loginUser.userNo == board.bwriter }">
-<script>

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>사진 게시판</title>

</head>
<body>
<jsp:include page="/WEB-INF/views/common/menubar.jsp" />
<div class="outer">
<div class="wrap">
<div class="board_area">
<div class="board_title">
<h1>사진 게시판</h1>
</div>
<div class="board_content">
<div class="subject">
<span> 글번호 : ${ board.bid }</span> 
<span> 조회수 : ${ board.bcount }</span>
<span> 작성자 : ${ board.userName }</span> 
<span> 작성일 : 
<fmt:formatDate value="${ board.createDate }" type="both"
pattern="yyy.MM.dd HH:mm:ss" />
</span> 
<span> 수정일 : 
<fmt:formatDate value="${ board.modifyDate }" type="both"
pattern="yyy.MM.dd HH:mm:ss" /></span> 
</div>
<div>
<h4>
<span class="title_span">&nbsp;</span> 분류
</h4>
<p>${ board.cname }</p>

<h4>
<span class="title_span">&nbsp;</span> 제목
</h4>
<p>${ board.btitle }</p>

<h4>
<span class="title_span">&nbsp;</span> 사진
</h4>

<c:forEach items="${ board.photoList}" var="photo">
<div class="photoList">
<img src="${ contextPath }${photo.filePath}${photo.changeName}">
<p>${ photo.originName }</p>
<p><button onclick="location.href='${contextPath }/gallery/download?fid=${ photo.fid }'">다운로드</button>
</div>


</c:forEach>
<h4>
<span class="title_span">&nbsp;</span> 내용
</h4>
<pre class="content">${ board.bcontent }</pre>
</div>
<div class="btn_area">
<button onclick="location.href='${contextPath}/gallery/list'">목록으로</button>

<c:if test="${ loginUser.userNo == board.bwriter }">
<button onclick="updateBoardView();">수정하기</button>
<button onclick="deleteBoard();">삭제하기</button>
</c:if>

</div>
</div>
</div>
</div>
</div>


<c:if test="${ loginUser.userNo == board.bwriter }">
<form name="boardForm" method="post">
<input type="hidden" name="bid" value="${board.bid }">
  </form>
</c:if>

<script>
function updateBoardView(){
document.forms.boardForm.action="${contextPath}/gallery/updateView";
document.forms.boardForm.submit();
}

function deleteBoard(){
if(confirm("이 게시글을 삭제하시겠습니까?")){
document.forms.boardForm.action="${contextPath}/gallery/delete";
document.forms.boardForm.submit();
}
}
</script>




</body>
</html>

 



2) GalleryDeleteServlet

생략

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int bid = Integer.parseInt(request.getParameter("bid"));

// Board, Attachment 테이블의 bid 일치하는 행 status Y -> N으로 변경
 // 서버에 저장된 이미지 파일의 정보를 알아와서 삭제 처리
List<Attachment> deletedPhotoList = new BoardService().deleteGallery(bid);


if(deletedPhotoList != null) {
// DB에서 Y -> N update 수행 완료되었으므로 서버의 파일 삭제
String root = request.getSession().getServletContext().getRealPath("/");
for(Attachment photo : deletedPhotoList) {
File deletedPhoto = new File(root + photo.getFilePath() + photo.getChangeName());
deletedPhoto.delete();
}
response.sendRedirect(request.getContextPath() + "/gallery/list");

} else {
request.setAttribute("message", "사진 게시판 게시글 삭제에 실패했습니다");
request.getRequestDispatcher("/WEB-INF/views/common/errorpage.jsp").forward(request, response);
}
}

}


3) BoardService
public List<Attachment> deleteGallery(int bid) {

  public List<Attachment> deleteGallery(int bid) {
      Connection conn = getConnection();
      
      List<Attachment> deletedPhotoList = boardDao.selectPhotoList(conn, bid);   /* 게시물 번호에 해당하는 이미지파일을 정보 얻어옴 */
      
      int boardResult = boardDao.deleteBoard(conn, bid);   /* 게시글 지우기 */
      
      int photoResult = boardDao.deletePhoto(conn, bid);   /* 이미지 지우기 */
      
      if(boardResult > 0 && photoResult == deletedPhotoList.size()) {   /* 보드테이블 삭제 & 이미지 삭제 1 ~ 3행 */
         commit(conn);
      } else {
         rollback(conn);
         deletedPhotoList = null;   /* 실패 시 이미지 삭제 방지 */
      }
      
      close(conn);
      
      return deletedPhotoList;
   }

 


4) BoardDao

 public List<Board> selectList(Connection conn, PageInfo pi, Search search) {
      PreparedStatement pstmt = null;
      ResultSet rset = null;
      String sql = boardQuery.getProperty("selectList");
      List<Board> boardList = new ArrayList<>();
      
      /* 추가 */
      // 검색 시 수행할 쿼리문 변경
      if(search.getSearchCondition() != null && search.getSearchValue() != null) {
         if(search.getSearchCondition().equals("title")) {
            sql = boardQuery.getProperty("selectTitleList");
         } else if(search.getSearchCondition().equals("content")) {
            sql = boardQuery.getProperty("selectContentList");
         } else if(search.getSearchCondition().equals("writer")) {
            sql = boardQuery.getProperty("selectWriterList");
         }
      }
      
      try {
         pstmt = conn.prepareStatement(sql);
         
         int startRow = (pi.getPage() - 1) * pi.getBoardLimit() + 1;
         int endRow = startRow + pi.getBoardLimit() - 1;
         
         /* 추가 : 변수로 처리 1, 2, 3 물음표 순서가 달라지니까 */
         int index = 1;
         // 검색 sql 실행 시
         if(search.getSearchCondition() != null && search.getSearchValue() != null) {
            pstmt.setString(index++, search.getSearchValue());   // 후위 연산 됨
         }
         
         pstmt.setInt(index++, startRow);
         pstmt.setInt(index, endRow);

         rset = pstmt.executeQuery();
         
         while(rset.next()) {
            Board board = new Board();
            board.setBid(rset.getInt("bid"));
            board.setCname(rset.getString("cname"));
            board.setBtitle(rset.getString("btitle"));
            board.setUserName(rset.getString("user_name"));
            board.setBcount(rset.getInt("bcount"));
            board.setCreateDate(rset.getDate("create_date"));
            boardList.add(board);
         }
      } catch (SQLException e) {
         e.printStackTrace();
      } finally {
         close(rset);
         close(pstmt);
      }
      
      return boardList;
   }



5) xml

  <entry key="selectPhotoList">
       SELECT
             FID
           , ORIGIN_NAME
           , CHANGE_NAME
           , FILE_PATH
           , FILE_LEVEL
           , DOWNLOAD_COUNT
         FROM ATTACHMENT
        WHERE BID = ?
          AND STATUS = 'Y'
        ORDER BY FID
    </entry>

 


6) service
int boardResult = boardDao.deleteBoard(conn, bid);

int photoResult = boardDao.deletePhoto(conn, bid);

  public List deleteGallery(int bid) {
      Connection conn = getConnection();
      
      List deletedPhotoList = boardDao.selectPhotoList(conn, bid);   /* 게시물 번호에 해당하는 이미지파일을 정보 얻어옴 */
      
      int boardResult = boardDao.deleteBoard(conn, bid);   /* 게시글 지우기 */
      
      int photoResult = boardDao.deletePhoto(conn, bid);   /* 이미지 지우기 */
      
      if(boardResult > 0 && photoResult == deletedPhotoList.size()) {   /* 보드테이블 삭제 & 이미지 삭제 1 ~ 3행 */
         commit(conn);
      } else {
         rollback(conn);
         deletedPhotoList = null;   /* 실패 시 이미지 삭제 방지 */
      }
      
      close(conn);
      
      return deletedPhotoList;
   }



7) dao
public int deletePhoto(Connection conn, int bid) {

 public int deleteBoard(Connection conn, int bid) {
      PreparedStatement pstmt = null;
      int result = 0;
      String sql = boardQuery.getProperty("deleteBoard");
      
      try {
         pstmt = conn.prepareStatement(sql);
         pstmt.setInt(1, bid);
         
         result = pstmt.executeUpdate();   
      } catch (SQLException e) {
         e.printStackTrace();
      } finally {
         close(pstmt);
      }
            
      return result;
   }

 


8. gallerydeleteServlet

package board.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import board.model.service.BoardService;
import board.model.vo.Attachment;

/**
 * Servlet implementation class GalleryDeleteServlet
 */
@WebServlet("/gallery/delete")
public class GalleryDeleteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GalleryDeleteServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int bid = Integer.parseInt(request.getParameter("bid"));

// Board, Attachment 테이블의 bid 일치하는 행 status Y -> N으로 변경
 // 서버에 저장된 이미지 파일의 정보를 알아와서 삭제 처리
List<Attachment> deletedPhotoList = new BoardService().deleteGallery(bid);


if(deletedPhotoList != null) {
// DB에서 Y -> N update 수행 완료되었으므로 서버의 파일 삭제
String root = request.getSession().getServletContext().getRealPath("/");
for(Attachment photo : deletedPhotoList) {
File deletedPhoto = new File(root + photo.getFilePath() + photo.getChangeName());
deletedPhoto.delete();
}
response.sendRedirect(request.getContextPath() + "/gallery/list");

} else {
request.setAttribute("message", "사진 게시판 게시글 삭제에 실패했습니다");
request.getRequestDispatcher("/WEB-INF/views/common/errorpage.jsp").forward(request, response);
}
}

}

2. 수정하기
1) gallerydeailview

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>사진 게시판</title>

</head>
<body>
<jsp:include page="/WEB-INF/views/common/menubar.jsp" />
<div class="outer">
<div class="wrap">
<div class="board_area">
<div class="board_title">
<h1>사진 게시판</h1>
</div>
<div class="board_content">
<div class="subject">
<span> 글번호 : ${ board.bid }</span> 
<span> 조회수 : ${ board.bcount }</span>
<span> 작성자 : ${ board.userName }</span> 
<span> 작성일 : 
<fmt:formatDate value="${ board.createDate }" type="both"
pattern="yyy.MM.dd HH:mm:ss" />
</span> 
<span> 수정일 : 
<fmt:formatDate value="${ board.modifyDate }" type="both"
pattern="yyy.MM.dd HH:mm:ss" /></span> 
</div>
<div>
<h4>
<span class="title_span">&nbsp;</span> 분류
</h4>
<p>${ board.cname }</p>

<h4>
<span class="title_span">&nbsp;</span> 제목
</h4>
<p>${ board.btitle }</p>

<h4>
<span class="title_span">&nbsp;</span> 사진
</h4>

<c:forEach items="${ board.photoList}" var="photo">
<div class="photoList">
<img src="${ contextPath }${photo.filePath}${photo.changeName}">
<p>${ photo.originName }</p>
<p><button onclick="location.href='${contextPath }/gallery/download?fid=${ photo.fid }'">다운로드</button>
</div>


</c:forEach>
<h4>
<span class="title_span">&nbsp;</span> 내용
</h4>
<pre class="content">${ board.bcontent }</pre>
</div>
<div class="btn_area">
<button onclick="location.href='${contextPath}/gallery/list'">목록으로</button>
<c:if test="${ loginUser.userNo == board.bwriter }">
<button onclick="updateBoardView();">수정하기</button>
<button onclick="deleteBoard();">삭제하기</button>
</c:if>
</div>
</div>
</div>
</div>
</div>


<c:if test="${ loginUser.userNo == board.bwriter }">
<form name="boardForm" method="post">
<input type="hidden" name="bid" value="${board.bid }">
  </form>
</c:if>

<script>
function updateBoardView(){
document.forms.boardForm.action="${contextPath}/gallery/updateView";
document.forms.boardForm.submit();
}

function deleteBoard(){
if(confirm("이 게시글을 삭제하시겠습니까?")){
document.forms.boardForm.action="${contextPath}/gallery/delete";
document.forms.boardForm.submit();
}
}
</script>




</body>
</html>



2) galleryUpdateViewServlet
-int bid = Integer.parseInt(request.getParameter("bid"));
여기서부터

생략 

   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      int bid = Integer.parseInt(request.getParameter("bid"));
      
      Board board = new BoardService().selectGallery(bid);
      
      if(board != null) {
         request.setAttribute("board", board);
         request.getRequestDispatcher("/WEB-INF/views/gallery/galleryUpdateView.jsp").forward(request, response);
         
      }else {
         request.setAttribute("message", "수정할 사진 게시판 게시글을 불러오는데 실패했습니다.");
         request.getRequestDispatcher("/WEB-INF/views/common/errorpage.jsp").forward(request, response);
         
      }
   }
}

 

 

 

   public Board selectGallery(int bid) {
      Connection conn = getConnection();
      
      /* Board 테이블 정보 조회 */
      Board board = boardDao.selectBoard(conn, bid);
      
      /* Attachment 테이블 정보 조회 */
      List<Attachment> photoList = boardDao.selectPhotoList(conn, bid);
      board.setPhotoList(photoList);
      
      close(conn);
      
      return board;
   }

 

 public Board selectBoard(Connection conn, int bid) {
      PreparedStatement pstmt = null;
      ResultSet rset = null;
      Board board = null;
      String sql = boardQuery.getProperty("selectBoard");
      
      try {
         pstmt = conn.prepareStatement(sql);
         pstmt.setInt(1, bid);
         rset = pstmt.executeQuery();
         
         if(rset.next()) {
            board = new Board();
            board.setBid(rset.getInt("bid"));
            board.setCid(rset.getInt("cid"));
            board.setCname(rset.getString("cname"));
            board.setBtitle(rset.getString("btitle"));
            board.setBcontent(rset.getString("bcontent"));
            board.setBwriter(rset.getInt("bwriter"));
            board.setUserName(rset.getString("user_name"));
            board.setBcount(rset.getInt("bcount"));
            board.setCreateDate(rset.getTimestamp("create_date"));
            board.setModifyDate(rset.getTimestamp("modify_date"));
         }
         
      } catch (SQLException e) {
         e.printStackTrace();
      } finally {
         close(rset);
         close(pstmt);
      }
      
      return board;
   }

 


3) galleryUpdateView 삽입
<option value="10" <c:if test="${ board.cid == 10 }">selected</c:if>>공통</option>

-<input type="text" name="title" value="${board.btitle }" required>
-<textarea class="textarea" rows="20" cols="100" name="content" required>${ board.bcontent }</textarea>

-<img src="${ contextPath }${ board.photoList.get(0).filePath }${board.photoList.get(0).changeName }">



-<form method="post" action="${contextPath }/gallery/update"
enctype="multipart/form-data">
<input type ="hidden" name="bid" value="${board.bid}">

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시판</title>

</head>
<body>
<jsp:include page="/WEB-INF/views/common/menubar.jsp" />
<div class="outer">
<div class="wrap">
<div class="board_area">
<div class="board_title">
<h1>게시글 수정</h1>
</div>
<div class="board_content">


<form method="post" action="${contextPath }/gallery/update"
enctype="multipart/form-data">
<input type ="hidden" name="bid" value="${board.bid}">
<c:forEach items="${board.photoList }" var="photo">
<input type="hidden" name="changeName" value="${ photo.changeName }">
</c:forEach>

<div class="content">
<h4>
<span class="title_span">&nbsp;</span> 분류
</h4>
<span class="input_area"> 
<select name="category">
<option value="10" <c:if test="${ board.cid == 10 }">selected</c:if>>공통</option>
<option value="20" <c:if test="${ board.cid == 20 }">selected</c:if>>운동</option>
<option value="30" <c:if test="${ board.cid == 30 }">selected</c:if>>등산</option>
<option value="40" <c:if test="${ board.cid == 40 }">selected</c:if>>게임</option>
<option value="50" <c:if test="${ board.cid == 50 }">selected</c:if>>낚시</option>
<option value="60" <c:if test="${ board.cid == 60 }">selected</c:if>>요리</option>
<option value="70" <c:if test="${ board.cid == 70 }">selected</c:if>>기타</option>
</select>
</span>

<h4>
<span class="title_span">&nbsp;</span> 제목
</h4>
<span class="input_area"> 
<input type="text" name="title" value="${board.btitle }" required>
</span>

<h4>
<span class="title_span">&nbsp;</span> 내용
</h4>

<textarea class="textarea" rows="20" cols="100" name="content"
required>${ board.bcontent }</textarea>


    <h4>
<span class="title_span">&nbsp;</span> 대표 이미지 수정
</h4>

<div class="image_area">
<img src="${ contextPath }${ board.photoList.get(0).filePath }${board.photoList.get(0).changeName }">
</div>

수정 파일 : <input type="file" name="thumbnail" accept="image/gif,image/jpeg,image/png">

<h4>
<span class="title_span">&nbsp;</span> 추가 이미지 수정(최대 2개)
</h4>

<div class="image_area">
<c:if test="${ board.photoList.size() > 1 }">
size: 개수
<img src="${ contextPath }${ board.photoList.get(1).filePath }${board.photoList.get(1).changeName }">
</c:if>
</div>

수정 파일 : <input type="file" name="contentImg1" accept="image/gif,image/jpeg,image/png"> 

<div class="image_area">
<c:if test="${ board.photoList.size() > 2 }">
<img src="${ contextPath }${ board.photoList.get(2).filePath }${board.photoList.get(2).changeName }">
</c:if>
</div>

수정 파일 : <input type="file" name="contentImg2" accept="image/gif,image/jpeg,image/png">
</div>

<div class="btn_area">
<button type="button">목록으로</button>
<button type="submit">수정하기</button>
</div>
</form>
</div>
</div>
</div>
</div>

<script src="${ contextPath }/resources/js/imagePreview.js"></script>

</body>
</html>

 

4) galleryupdateServlet
int result = new BoardService().updateGallery(board); 까지

생략
      
      
   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      /* enctype이 multipart/form-data 로 전송되었는지 확인*/
      if(!ServletFileUpload.isMultipartContent(request)) {
         request.setAttribute("message", "잘못된 전송입니다.");
         request.getRequestDispatcher("/WEB-INF/views/common/errorpage.jsp").forward(request, response);
         return;
      }
      
      int maxSize = 1024*1024*10;
      String root = request.getSession().getServletContext().getRealPath("/");
      String savePath = root + "resources\\uploadFiles\\";
      /* input type file에 첨부 된 파일 서버에 저장 됨*/
      MultipartRequest multiRequest
         = new MultipartRequest(request, savePath, maxSize, "UTF-8", new MyFileRenamePolicy());
      
      
      /* Board 테이블 수정 값 설정*/
      Board board = new Board();
      board.setBid(Integer.parseInt(multiRequest.getParameter("bid")));
      board.setCid(Integer.parseInt(multiRequest.getParameter("category")));
      board.setBtitle(multiRequest.getParameter("title"));
      board.setBcontent(multiRequest.getParameter("content"));
      
      
      /* Attachment 테이블 수정 값 설정*/
      List<Attachment> photoList = new ArrayList<>();
      String[] fileNames = {"thumbnail", "contentImg1", "contentImg2"};
      String[] changeNames = multiRequest.getParameterValues("changeName");
      
      for(int i = 0 ; i < fileNames.length; i++) {
         // 넘어온 파일이 없는 경우 수정 사항이 없으므로 continue로 반복문 다음으로 진행
         if(multiRequest.getFilesystemName(fileNames[i])== null)
            continue;
        
         
         // 수정을 위해 첨부 된 파일이 있는 경우
         Attachment photo = new Attachment();
         photo.setFilePath("/resources/uploadFiles/");
         photo.setOriginName(multiRequest.getOriginalFileName(fileNames[i]));
         photo.setChangeName(multiRequest.getFilesystemName(fileNames[i]));
         
         if(i == 0 ) {
            photo.setFileLevel(0);
         }else {
            photo.setFileLevel(1);
         }
      
         // 원래 저장된 파일이 있었다면 -> DB에서 update 처리 & 서버에서 기존 파일 delete 처리
         if(changeNames.length >= i+1) {
     1 / 1 / 1
     2 / 1 2 / 0 1
     3 / 1 2 3 / 0 1 2


            photo.setDeletedName(changeNames[i]);
         }
         photoList.add(photo);
      }
      board.setPhotoList(photoList);
      
      
      
      int result = new BoardService().updateGallery(board);
      
      
      
      if(result> 0) {
      // 수정 성공시 덮어쓰기된 사진 삭제
       for(Attachment photo : photoList) {
       if(photo.getDeletedName() != null) {
      File deletedFile = new File(savePath + photo.getDeletedName());
      deletedFile.delete();
       }
       }
       
         response.sendRedirect(request.getContextPath()+"/gallery/detail?bid="
                                 +Integer.parseInt(multiRequest.getParameter("bid")));
      }else {
       
      // 수정 실패시 수정을 위해 첨부된 사진 삭제
       for(Attachment photo : photoList) {
       File failedFile = new File(savePath + photo.getChangeName());
       failedFile.delete();
       }
         request.setAttribute("message", "사진 게시글 수정에 실패했습니다.");
         request.getRequestDispatcher("/WEB-INF/views/common/errorpage.jsp").forward(request, response);
      }
   }

}
 

 


5. service

public int updateGallery(Board board) {
      Connection conn = getConnection();
      
      /* Board 테이블 수정 */
      int boardResult = boardDao.updateBoard(conn, board);
      
      // 실행 결과
      int updatePhotoResult = 0;
      int insertPhotoResult = 0;
      // 수행 해야할 리스트 갯수
      int updateListCount = 0;
      int insertListCount = 0;
      
      /* Attachment 테이블 수정 */
      for(Attachment photo : board.getPhotoList()) {
         if(photo.getDeletedName() != null) {
            /* 기존에 있던 파일을 덮어쓰기 - update */
            updatePhotoResult += boardDao.updatePhoto(conn, photo);
            updateListCount++;
            System.out.println("update : " + photo);
            System.out.println("updatePhotoResult : " + updatePhotoResult);
         }else {
            /* 새로 첨부 된 파일을 추가하기 - insert */
            insertPhotoResult += boardDao.insertAddedPhoto(conn, board.getBid(), photo);
            insertListCount++;
//             System.out.println("update : " + photo);
//             System.out.println("insertPhotoResult : " + insertPhotoResult);
         }
      }
      
      int result = 0;
      if(boardResult > 0 
            && updatePhotoResult == updateListCount 
            && insertPhotoResult == insertListCount) {
         result = 1;
         commit(conn);
      }else {
         rollback(conn);
      }
      
      return result;
   }
}

 

6. boardDao

 public int updatePhoto(Connection conn, Attachment photo) {
      PreparedStatement pstmt = null;
      int result = 0;
      String sql = boardQuery.getProperty("updatePhoto");
      
      try {
         pstmt = conn.prepareStatement(sql);
         
         pstmt.setString(1, photo.getOriginName());
         pstmt.setString(2, photo.getChangeName());
         pstmt.setString(3, photo.getDeletedName());
         
         result = pstmt.executeUpdate();
      } catch (SQLException e) {
         e.printStackTrace();
      } finally {
         close(pstmt);
      }
      
      return result;
   }

 

7) 

 <entry key="updatePhoto">
       UPDATE ATTACHMENT
          SET ORIGIN_NAME = ?
            , CHANGE_NAME = ?
            , UPLOAD_DATE = SYSDATE
            , DOWNLOAD_COUNT = 0
        WHERE CHANGE_NAME = ?
    </entry>

 

 

8)

public int updateGallery(Board board) {
      Connection conn = getConnection();
      
      /* Board 테이블 수정 */
      int boardResult = boardDao.updateBoard(conn, board);
      
      // 실행 결과
      int updatePhotoResult = 0;
      int insertPhotoResult = 0;
      // 수행 해야할 리스트 갯수
      int updateListCount = 0;
      int insertListCount = 0;
      
      /* Attachment 테이블 수정 */
      for(Attachment photo : board.getPhotoList()) {
         if(photo.getDeletedName() != null) {
            /* 기존에 있던 파일을 덮어쓰기 - update */
            updatePhotoResult += boardDao.updatePhoto(conn, photo);
            updateListCount++;
            System.out.println("update : " + photo);
            System.out.println("updatePhotoResult : " + updatePhotoResult);
         }else {
            /* 새로 첨부 된 파일을 추가하기 - insert */
            insertPhotoResult += boardDao.insertAddedPhoto(conn, board.getBid(), photo);
            insertListCount++;
//             System.out.println("update : " + photo);
//             System.out.println("insertPhotoResult : " + insertPhotoResult);
         }
      }
      
      int result = 0;
      if(boardResult > 0 
            && updatePhotoResult == updateListCount 
            && insertPhotoResult == insertListCount) {
         result = 1;
         commit(conn);
      }else {
         rollback(conn);
      }
      
      return result;
   }

 

9)

  public int insertAddedPhoto(Connection conn, int bid, Attachment photo) {
      PreparedStatement pstmt = null;
      int result = 0;
      String sql = boardQuery.getProperty("insertAddedPhoto");
      
      try {
         pstmt = conn.prepareStatement(sql);
         
            pstmt.setInt(1,  bid);
            pstmt.setString(2,  photo.getOriginName());
            pstmt.setString(3,  photo.getChangeName());
            pstmt.setString(4, photo.getFilePath());
            pstmt.setInt(5, photo.getFileLevel());
            
            result = pstmt.executeUpdate();
      } catch (SQLException e) {
         e.printStackTrace();
      } finally {
         close(pstmt);
      }
      return result;
   }

 

 <entry key="insertAddedPhoto">
         INSERT
           INTO ATTACHMENT
           ( 
                 FID
              , BID
              , ORIGIN_NAME
              , CHANGE_NAME
              , FILE_PATH
              , UPLOAD_DATE
              , FILE_LEVEL
              , DOWNLOAD_COUNT
              , STATUS
           )
           VALUES
           (
               SEQ_FID.NEXTVAL
             , ?
             , ?
             , ?
             , ?
             , SYSDATE
             , ?
             , DEFAULT
             , DEFAULT
           )
    </entry>

'웹개발 수업 > Server' 카테고리의 다른 글

[목록]  (0) 2021.11.06
[전체 복습]읽으시오  (0) 2021.11.06
[Day +86 / Server]내용 추가하세요  (0) 2021.10.27
[Day +85 / Server]Server 2교시 시험  (0) 2021.10.26
[Day +85 / Server]Server 1차 시험  (0) 2021.10.26