ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring] 게시판 만들기(21) - 게시글 수정(첨부파일 등록 및 삭제)
    Spring/4.3.x - 게시판 만들기 2019. 5. 10. 11:17
    반응형

    1. Front-End 파일 수정

    1_1. boardUpdate.jsp 수정

    1_1)게시글 등록 시에 첨부파일을 포함하지 않은 경우 게시글 수정 시에 첨부파일을 등록할 수 있도록 수정

     - Form 태그 속성 및 ajax 호출 방식을 변경하세요. 

     - 첨부파일을 등록하는 로직은 이미 구현되어 있으므로, 게시글 수정 시 첨부파일을 최초로 등록하거나 삭제 후 재등록 시 files 정보만 넘겨주시면 벡엔드에서 따로 작업할 내용은 없습니다.

     

    1_2)게시글 등록 시에 첨부파일을 포함한 경우 게시글 수정 시에 첨부파일을 삭제할 수 있도록 수정

     - 삭제할 첨부파일의 정보를 저장할 전연변수 또는 input 태그를 선언하세요. (<input id="delete_file" />를 추가) 

     - TB_BOARD_FILE 테이블에 PK는 BOARD_SEQ, FILE_NO이므로 delete 또는 update를 위해 해당 내용을 전역변수 또는 input 태그에 저장해주세요. (!를 구분자로 값을 저장 - BOARD_SEQ!FILE_NO)

    더보기
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    <%@ 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="fn" uri="http://java.sun.com/jsp/jstl/functions" %>  
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>게시판 수정</title>
    <%    
        String boardSeq = request.getParameter("boardSeq");        
    %>
     
    <c:set var="boardSeq" value="<%=boardSeq%>"/<!-- 게시글 번호 -->
     
    <!-- 공통 CSS -->
    <link rel="stylesheet" type="text/css" href="/css/common/common.css"/>
     
    <!-- 공통 JavaScript -->
    <script type="text/javascript" src="/js/common/jquery.js"></script>
    <script type="text/javascript" src="/js/common/jquery.form.js"></script>
    <script type="text/javascript">
        
        $(document).ready(function(){        
            getBoardDetail();        
        });
        
        /** 게시판 - 목록 페이지 이동 */
        function goBoardList(){                
            location.href = "/board/boardList";
        }
        
        /** 게시판 - 상세 조회  */
        function getBoardDetail(boardSeq){
            
            var boardSeq = $("#board_seq").val();
     
            if(boardSeq != ""){
                
                $.ajax({    
                    
                    url        : "/board/getBoardDetail",
                    data    : $("#boardForm").serialize(),
                    dataType: "JSON",
                    cache   : false,
                    async   : true,
                    type    : "POST",    
                    success : function(obj) {
                        getBoardDetailCallback(obj);                
                    },           
                    error     : function(xhr, status, error) {}
                    
                 });
                
            } else {
                alert("오류가 발생했습니다.\n관리자에게 문의하세요.");
            }    
        }
        
        /** 게시판 - 상세 조회  콜백 함수 */
        function getBoardDetailCallback(obj){
                    
            if(obj != null){                                
                                
                var boardSeq        = obj.board_seq; 
                var boardReRef         = obj.board_re_ref; 
                var boardReLev         = obj.board_re_lev; 
                var boardReSeq         = obj.board_re_seq; 
                var boardWriter     = obj.board_writer; 
                var boardSubject     = obj.board_subject; 
                var boardContent     = obj.board_content; 
                var boardHits         = obj.board_hits;
                var delYn             = obj.del_yn; 
                var insUserId         = obj.ins_user_id;
                var insDate         = obj.ins_date; 
                var updUserId         = obj.upd_user_id;
                var updDate         = obj.upd_date;
                var files            = obj.files;        
                var filesLen        = files.length;
                                    
                $("#board_subject").val(boardSubject);            
                $("#board_content").val(boardContent);
                $("#board_writer").text(boardWriter);
                
                var fileStr = "";
                
                if(filesLen > 0){
                    
                    for(var a=0; a<filesLen; a++){
                        
                        var boardSeq    = files[a].board_seq;
                        var fileNo         = files[a].file_no;
                        var fileNameKey = files[a].file_name_key;
                        var fileName     = files[a].file_name;
                        var filePath     = files[a].file_path;
                        var fileSize     = files[a].file_size;
                        var remark         = files[a].remark;
                        var delYn         = files[a].del_yn;
                        var insUserId     = files[a].ins_user_id;
                        var insDate     = files[a].ins_date;
                        var updUserId     = files[a].upd_user_id;
                        var updDate     = files[a].upd_date;
                        
                        fileStr += "<a href='/board/fileDownload?fileNameKey="+encodeURI(fileNameKey)+"&fileName="+encodeURI(fileName)+"&filePath="+encodeURI(filePath)+"'>" + fileName + "</a>";
                        fileStr += "<button type='button' class='btn black ml15' style='padding:3px 5px 6px 5px;' onclick='javascript:setDeleteFile("+ boardSeq +", "+ fileNo +")'>X</button>";
                    }            
                                    
                } else {
                    
                    fileStr = "<input type='file' id='files[0]' name='files[0]' value=''></td>";
                }
                
                $("#file_td").html(fileStr);
                
            } else {            
                alert("등록된 글이 존재하지 않습니다.");
                return;
            }        
        }
        
        /** 게시판 - 수정  */
        function updateBoard(){
     
            var boardSubject = $("#board_subject").val();
            var boardContent = $("#board_content").val();
                
            if (boardSubject == ""){            
                alert("제목을 입력해주세요.");
                $("#board_subject").focus();
                return;
            }
            
            if (boardContent == ""){            
                alert("내용을 입력해주세요.");
                $("#board_content").focus();
                return;
            }
            
            var yn = confirm("게시글을 수정하시겠습니까?");        
            if(yn){
                    
                var filesChk = $("input[name='files[0]']").val();
                if(filesChk == ""){
                    $("input[name='files[0]']").remove();
                }
                
                $("#boardForm").ajaxForm({
                
                    url        : "/board/updateBoard",
                    enctype    : "multipart/form-data",
                    cache   : false,
                    async   : true,
                    type    : "POST",                         
                    success : function(obj) {
                        updateBoardCallback(obj);                
                    },           
                    error     : function(xhr, status, error) {}
                    
                }).submit();
            }
        }
        
        /** 게시판 - 수정 콜백 함수 */
        function updateBoardCallback(obj){
        
            if(obj != null){        
                
                var result = obj.result;
                
                if(result == "SUCCESS"){                
                    alert("게시글 수정을 성공하였습니다.");                
                    goBoardList();                 
                } else {                
                    alert("게시글 수정을 실패하였습니다.");    
                    return;
                }
            }
        }
        
        /** 게시판 - 삭제할 첨부파일 정보 */
        function setDeleteFile(boardSeq, fileSeq){
            
            var deleteFile = boardSeq + "!" + fileSeq;        
            $("#delete_file").val(deleteFile);
                    
            var fileStr = "<input type='file' id='files[0]' name='files[0]' value=''>";        
            $("#file_td").html(fileStr);        
        }
            
    </script>
    </head>
    <body>
    <div id="wrap">
        <div id="container">
            <div class="inner">    
                <h2>게시글 상세</h2>
                <form id="boardForm" name="boardForm" action="/board/updateBoard" enctype="multipart/form-data" method="post" onsubmit="return false;">    
                    <table width="100%" class="table02">
                    <caption><strong><span class="t_red">*</span> 표시는 필수입력 항목입니다.</strong></caption>
                        <colgroup>
                             <col width="20%">
                            <col width="*">
                        </colgroup>
                        <tbody id="tbody">
                           <tr>
                                <th>제목<span class="t_red">*</span></th>
                                <td><input id="board_subject" name="board_subject" value="" class="tbox01"/></td>
                            </tr>
                             <tr>
                                <th>작성자</th>
                                <td id="board_writer"></td>
                            </tr>
                            <tr>
                                <th>내용<span class="t_red">*</span></th>
                                <td colspan="3"><textarea id="board_content" name="board_content" cols="50" rows="5" class="textarea01"></textarea></td>
                            </tr>
                            <tr>
                                <th>첨부파일</th>
                                <td colspan="3" id="file_td"><input type="file" id="files[0]" name="files[0]" value=""></td>
                            </tr>
                        </tbody>
                    </table>    
                    <input type="hidden" id="board_seq"        name="board_seq"    value="${boardSeq}"/<!-- 게시글 번호 -->
                    <input type="hidden" id="search_type"    name="search_type"    value="U"/<!-- 조회 타입 - 상세(S)/수정(U) -->
                    <input type="hidden" id="delete_file"    name="delete_file"    value=""/<!-- 삭제할 첨부파일 -->
                </form>
                <div class="btn_right mt15">
                    <button type="button" class="btn black mr5" onclick="javascript:goBoardList();">목록으로</button>
                    <button type="button" class="btn black" onclick="javascript:updateBoard();">수정하기</button>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>
    cs

     

    2. Back-End 파일 수정

    2_1. BoardForm.java 수정

     삭제할 첨부파일의 정보를 처리할 get/set 메소드를 추가하세요. (String delete_file를 추가)

    더보기

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    package com.spring.board.form;
     
    import java.util.Date;
    import java.util.List;
     
    import org.springframework.web.multipart.MultipartFile;
     
    public class BoardForm extends CommonForm {
     
        List<MultipartFile> files;
        int board_seq;
        int board_parent_seq;
        int board_re_ref;
        int board_re_lev;
        int board_re_seq;
        String board_writer;
        String board_subject;
        String board_content;
        int board_hits;
        String del_yn;
        String ins_user_id;
        Date ins_date;
        String upd_user_id;
        Date upd_date;
        String search_type;
        String board_file;
        String delete_file;
     
        public List<MultipartFile> getFiles() {
            return files;
        }
     
        public void setFiles(List<MultipartFile> files) {
            this.files = files;
        }
     
        public int getBoard_seq() {
            return board_seq;
        }
     
        public void setBoard_seq(int board_seq) {
            this.board_seq = board_seq;
        }
     
        public int getBoard_parent_seq() {
            return board_parent_seq;
        }
     
        public void setBoard_parent_seq(int board_parent_seq) {
            this.board_parent_seq = board_parent_seq;
        }
     
        public int getBoard_re_ref() {
            return board_re_ref;
        }
     
        public void setBoard_re_ref(int board_re_ref) {
            this.board_re_ref = board_re_ref;
        }
     
        public int getBoard_re_lev() {
            return board_re_lev;
        }
     
        public void setBoard_re_lev(int board_re_lev) {
            this.board_re_lev = board_re_lev;
        }
     
        public int getBoard_re_seq() {
            return board_re_seq;
        }
     
        public void setBoard_re_seq(int board_re_seq) {
            this.board_re_seq = board_re_seq;
        }
     
        public String getBoard_writer() {
            return board_writer;
        }
     
        public void setBoard_writer(String board_writer) {
            this.board_writer = board_writer;
        }
     
        public String getBoard_subject() {
            return board_subject;
        }
     
        public void setBoard_subject(String board_subject) {
            this.board_subject = board_subject;
        }
     
        public String getBoard_content() {
            return board_content;
        }
     
        public void setBoard_content(String board_content) {
            this.board_content = board_content;
        }
     
        public int getBoard_hits() {
            return board_hits;
        }
     
        public void setBoard_hits(int board_hits) {
            this.board_hits = board_hits;
        }
     
        public String getDel_yn() {
            return del_yn;
        }
     
        public void setDel_yn(String del_yn) {
            this.del_yn = del_yn;
        }
     
        public String getIns_user_id() {
            return ins_user_id;
        }
     
        public void setIns_user_id(String ins_user_id) {
            this.ins_user_id = ins_user_id;
        }
     
        public Date getIns_date() {
            return ins_date;
        }
     
        public void setIns_date(Date ins_date) {
            this.ins_date = ins_date;
        }
     
        public String getUpd_user_id() {
            return upd_user_id;
        }
     
        public void setUpd_user_id(String upd_user_id) {
            this.upd_user_id = upd_user_id;
        }
     
        public Date getUpd_date() {
            return upd_date;
        }
     
        public void setUpd_date(Date upd_date) {
            this.upd_date = upd_date;
        }
     
        public String getSearch_type() {
            return search_type;
        }
     
        public void setSearch_type(String search_type) {
            this.search_type = search_type;
        }
     
        public String getBoard_file() {
            return board_file;
        }
     
        public void setBoard_file(String board_file) {
            this.board_file = board_file;
        }
     
        public String getDelete_file() {
            return delete_file;
        }
     
        public void setDelete_file(String delete_file) {
            this.delete_file = delete_file;
        }
    }
     
    cs

     

    2_2. BoardService.java 수정

    1_1)게시글 등록 시에 첨부파일을 포함하지 않은 경우 게시글 수정 시에 첨부파일을 등록할 수 있도록 수정

     - insertBoard 메소드에서 첨부파일을 등록하는 boardDao.insertBoardFile() 부분을 updateBoard 메소드에 추가해주세요.

     

    1_2)게시글 등록 시에 첨부파일을 포함한 경우 게시글 수정 시에 첨부파일을 삭제할 수 있도록 수정

     - delete_file에는 !를 구분자로 BOARD_SEQ, FILE_NO 정보가 저장되어 있으므로 split() 메소드를 통해 값을 구해주세요. 

    더보기
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    package com.spring.board.service;
     
    import java.io.File;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.UUID;
     
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;
     
    import com.spring.board.common.PagingUtil;
    import com.spring.board.common.ResultUtil;
    import com.spring.board.dao.BoardDao;
    import com.spring.board.dto.BoardDto;
    import com.spring.board.dto.CommonDto;
    import com.spring.board.form.BoardFileForm;
    import com.spring.board.form.BoardForm;
    import com.spring.board.form.CommonForm;
     
    @Service
    public class BoardService {
     
        @Autowired
        private BoardDao boardDao;
     
        /** 게시판 - 목록 조회 */
        public ResultUtil getBoardList(BoardForm boardForm) throws Exception {
     
            ResultUtil resultUtil = new ResultUtil();
     
            CommonDto commonDto = new CommonDto();
     
            int totalCount = boardDao.getBoardCnt(boardForm);
            if (totalCount != 0) {
                CommonForm commonForm = new CommonForm();
                commonForm.setFunction_name(boardForm.getFunction_name());
                commonForm.setCurrent_page_no(boardForm.getCurrent_page_no());
                commonForm.setCount_per_page(10);
                commonForm.setCount_per_list(10);
                commonForm.setTatal_list_count(totalCount);
                commonDto = PagingUtil.setPageUtil(commonForm);
            }
     
            boardForm.setLimit(commonDto.getLimit());
            boardForm.setOffset(commonDto.getOffset());
     
            List<BoardDto> list = boardDao.getBoardList(boardForm);
     
            HashMap<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("list", list);
            resultMap.put("totalCount", totalCount);
            resultMap.put("pagination", commonDto.getPagination());
     
            resultUtil.setData(resultMap);
            resultUtil.setState("SUCCESS");
     
            return resultUtil;
        }
     
        /** 게시판 - 상세 조회 */
        public BoardDto getBoardDetail(BoardForm boardForm) throws Exception {
     
            BoardDto boardDto = new BoardDto();
     
            String searchType = boardForm.getSearch_type();
     
            if ("S".equals(searchType)) {
     
                boardDao.updateBoardHits(boardForm);
            }
     
            boardDto = boardDao.getBoardDetail(boardForm);
     
            BoardFileForm boardFileForm = new BoardFileForm();
            boardFileForm.setBoard_seq(boardForm.getBoard_seq());
     
            boardDto.setFiles(boardDao.getBoardFileList(boardFileForm));
     
            return boardDto;
        }
     
        /** 게시판 - 등록 */
        public BoardDto insertBoard(BoardForm boardForm) throws Exception {
     
            BoardDto boardDto = new BoardDto();
     
            int insertCnt = 0;
     
            int boardReRef = boardDao.getBoardReRef(boardForm);
            boardForm.setBoard_re_ref(boardReRef);
     
            insertCnt = boardDao.insertBoard(boardForm);
     
            List<BoardFileForm> boardFileList = getBoardFileInfo(boardForm);
            for (BoardFileForm boardFileForm : boardFileList) {
                boardDao.insertBoardFile(boardFileForm);
            }
     
            if (insertCnt > 0) {
                boardDto.setResult("SUCCESS");
            } else {
                boardDto.setResult("FAIL");
            }
     
            return boardDto;
        }
     
        /** 게시판 - 첨부파일 정보 조회 */
        public List<BoardFileForm> getBoardFileInfo(BoardForm boardForm) throws Exception {
     
            List<MultipartFile> files = boardForm.getFiles();
     
            List<BoardFileForm> boardFileList = new ArrayList<BoardFileForm>();
     
            BoardFileForm boardFileForm = new BoardFileForm();
     
            int boardSeq = boardForm.getBoard_seq();
            String fileName = null;
            String fileExt = null;
            String fileNameKey = null;
            String fileSize = null;
            // 파일이 저장될 Path 설정
            String filePath = "C:\\board\\file";
     
            if (files != null && files.size() > 0) {
     
                File file = new File(filePath);
     
                // 디렉토리가 없으면 생성
                if (file.exists() == false) {
                    file.mkdirs();
                }
     
                for (MultipartFile multipartFile : files) {
     
                    fileName = multipartFile.getOriginalFilename();
                    fileExt = fileName.substring(fileName.lastIndexOf("."));
                    // 파일명 변경(uuid로 암호화) + 확장자
                    fileNameKey = getRandomString() + fileExt;
                    fileSize = String.valueOf(multipartFile.getSize());
     
                    // 설정한 Path에 파일 저장
                    file = new File(filePath + "/" + fileNameKey);
     
                    multipartFile.transferTo(file);
     
                    boardFileForm = new BoardFileForm();
                    boardFileForm.setBoard_seq(boardSeq);
                    boardFileForm.setFile_name(fileName);
                    boardFileForm.setFile_name_key(fileNameKey);
                    boardFileForm.setFile_path(filePath);
                    boardFileForm.setFile_size(fileSize);
                    boardFileList.add(boardFileForm);
                }
            }
     
            return boardFileList;
        }
     
        /** 게시판 - 삭제 */
        public BoardDto deleteBoard(BoardForm boardForm) throws Exception {
     
            BoardDto boardDto = new BoardDto();
     
            int deleteCnt = boardDao.deleteBoard(boardForm);
     
            if (deleteCnt > 0) {
                boardDto.setResult("SUCCESS");
            } else {
                boardDto.setResult("FAIL");
            }
     
            return boardDto;
        }
     
        /** 게시판 - 수정 */
        public BoardDto updateBoard(BoardForm boardForm) throws Exception {
     
            BoardDto boardDto = new BoardDto();
     
            int updateCnt = boardDao.updateBoard(boardForm);
     
            String deleteFile = boardForm.getDelete_file();
            if (!"".equals(deleteFile)) {
     
                String[] deleteFileInfo = deleteFile.split("!");
     
                int boardSeq = Integer.parseInt(deleteFileInfo[0]);
                int fileNo = Integer.parseInt(deleteFileInfo[1]);
     
                BoardFileForm deleteBoardFileForm = new BoardFileForm();
                deleteBoardFileForm.setBoard_seq(boardSeq);
                deleteBoardFileForm.setFile_no(fileNo);
                
                boardDao.deleteBoardFile(deleteBoardFileForm);
            }
     
            List<BoardFileForm> boardFileList = getBoardFileInfo(boardForm);
            for (BoardFileForm boardFileForm : boardFileList) {
                boardDao.insertBoardFile(boardFileForm);
            }
            
            if (updateCnt > 0) {
                boardDto.setResult("SUCCESS");
            } else {
                boardDto.setResult("FAIL");
            }
     
            return boardDto;
        }
     
        /** 게시판 - 답글 등록 */
        public BoardDto insertBoardReply(BoardForm boardForm) throws Exception {
     
            BoardDto boardDto = new BoardDto();
     
            BoardDto boardReplayInfo = boardDao.getBoardReplyInfo(boardForm);
     
            boardForm.setBoard_seq(boardReplayInfo.getBoard_seq());
            boardForm.setBoard_re_lev(boardReplayInfo.getBoard_re_lev());
            boardForm.setBoard_re_ref(boardReplayInfo.getBoard_re_ref());
            boardForm.setBoard_re_seq(boardReplayInfo.getBoard_re_seq());
     
            int insertCnt = 0;
     
            insertCnt += boardDao.updateBoardReSeq(boardForm);
     
            insertCnt += boardDao.insertBoardReply(boardForm);
     
            if (insertCnt > 0) {
                boardDto.setResult("SUCCESS");
            } else {
                boardDto.setResult("FAIL");
            }
     
            return boardDto;
        }
     
        /** 32글자의 랜덤한 문자열(숫자포함) 생성 */
        public static String getRandomString() {
     
            return UUID.randomUUID().toString().replaceAll("-""");
        }
    }
     
    cs

     

    2_3. BoardDao.java 수정

     첨부파일을 삭제하기 위한 dao를 추가하세요.

    더보기

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    package com.spring.board.dao;
     
    import java.util.List;
     
    import javax.annotation.Resource;
     
    import org.apache.ibatis.session.SqlSession;
    import org.springframework.stereotype.Repository;
     
    import com.spring.board.dto.BoardDto;
    import com.spring.board.dto.BoardFileDto;
    import com.spring.board.form.BoardFileForm;
    import com.spring.board.form.BoardForm;
     
    @Repository
    public class BoardDao {
     
        @Resource(name = "sqlSession")
        private SqlSession sqlSession;
     
        private static final String NAMESPACE = "com.spring.board.boardMapper";
     
        /** 게시판 - 목록 수 */
        public int getBoardCnt(BoardForm boardForm) throws Exception { 
            return sqlSession.selectOne(NAMESPACE + ".getBoardCnt", boardForm);
        }
     
        /** 게시판 - 목록 조회 */
        public List<BoardDto> getBoardList(BoardForm boardForm) throws Exception { 
            return sqlSession.selectList(NAMESPACE + ".getBoardList", boardForm);
        }
     
        /** 게시판 - 조회 수 수정 */
        public int updateBoardHits(BoardForm boardForm) throws Exception { 
            return sqlSession.update(NAMESPACE + ".updateBoardHits", boardForm);
        }
     
        /** 게시판 - 상세 조회 */
        public BoardDto getBoardDetail(BoardForm boardForm) throws Exception { 
            return sqlSession.selectOne(NAMESPACE + ".getBoardDetail", boardForm);
        }
        
        /** 게시판 - 첨부파일 조회 */
        public List<BoardFileDto> getBoardFileList(BoardFileForm boardFileForm) throws Exception { 
            return sqlSession.selectList(NAMESPACE + ".getBoardFileList", boardFileForm);
        }
     
        /** 게시판 - 그룹 번호 조회 */
        public int getBoardReRef(BoardForm boardForm) throws Exception { 
            return sqlSession.selectOne(NAMESPACE + ".getBoardReRef", boardForm);
        }
        
        /** 게시판 - 등록 */
        public int insertBoard(BoardForm boardForm) throws Exception {
            return sqlSession.insert(NAMESPACE + ".insertBoard", boardForm);
        }
        
        /** 게시판 - 첨부파일 등록 */
        public int insertBoardFile(BoardFileForm boardFileForm) throws Exception {
            return sqlSession.insert(NAMESPACE + ".insertBoardFile", boardFileForm);
        }
     
        /** 게시판 - 등록 실패(트랜잭션 테스트) */
        public int insertBoardFail(BoardForm boardForm) throws Exception {
            return sqlSession.insert(NAMESPACE + ".insertBoardFail", boardForm);
        }
     
        /** 게시판 - 삭제 */
        public int deleteBoard(BoardForm boardForm) throws Exception { 
            return sqlSession.delete(NAMESPACE + ".deleteBoard", boardForm);
        }
     
        /** 게시판 - 수정 */
        public int updateBoard(BoardForm boardForm) throws Exception { 
            return sqlSession.update(NAMESPACE + ".updateBoard", boardForm);
        }
        
        /** 게시판 - 답글 정보  조회 */
        public BoardDto getBoardReplyInfo(BoardForm boardForm) throws Exception {
            return sqlSession.selectOne(NAMESPACE + ".getBoardReplyInfo", boardForm);
        }
        
        /** 게시판 - 답글의 순서 수정 */
        public int updateBoardReSeq(BoardForm boardForm) throws Exception { 
            return sqlSession.update(NAMESPACE + ".updateBoardReSeq", boardForm);
        }
        
        /** 게시판 - 답글 등록 */
        public int insertBoardReply(BoardForm boardForm) throws Exception {
            return sqlSession.insert(NAMESPACE + ".insertBoardReply", boardForm);
        }
        
        /** 게시판 - 첨부파일 삭제 */
        public int deleteBoardFile(BoardFileForm boardFileForm) throws Exception {
            return sqlSession.update(NAMESPACE + ".deleteBoardFile", boardFileForm);
        }    
    }
    cs

     

    2_4. boardMapper.xml

    TB_BOARD_FILE에 데이터를 삭제하려면 DELETE문을 작성하시고, TB_BOARD_FILE에 DEL_YN 컬럼으로 데이터를 관리하려면 UPDATE문을 작성하세요.

    더보기
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     
    <mapper namespace="com.spring.board.boardMapper">
     
        <select id="getBoardCnt" parameterType="com.spring.board.form.BoardForm" resultType="int">
        
            SELECT COUNT(*)
            FROM BOARD.TB_BOARD
        
        </select>
        
        <select id="getBoardList" parameterType="com.spring.board.form.BoardForm" resultType="com.spring.board.dto.BoardDto">
        
            SELECT *
            FROM ( SELECT BOARD_SEQ 
                        , BOARD_RE_REF 
                        , BOARD_RE_LEV 
                        , BOARD_RE_SEQ 
                        , BOARD_WRITER 
                        , BOARD_SUBJECT 
                        , BOARD_CONTENT 
                        , BOARD_HITS
                        , DEL_YN 
                        , INS_USER_ID
                        , CAST( DATE_FORMAT( INS_DATE, '%Y-%m-%d %H:%i:%s' ) AS CHAR(19) ) AS INS_DATE
                        , UPD_USER_ID
                        , CAST( DATE_FORMAT( UPD_DATE, '%Y-%m-%d %H:%i:%s' ) AS CHAR(19) ) AS UPD_DATE  
                   FROM BOARD.TB_BOARD
                   ORDER BY BOARD_RE_REF DESC, BOARD_RE_SEQ ASC
                  ) T1
            LIMIT #{limit} OFFSET #{offset}
        
        </select>
        
        <delete id="updateBoardHits" parameterType="com.spring.board.form.BoardForm">
        
            UPDATE BOARD.TB_BOARD 
               SET BOARD_HITS = BOARD_HITS + 1             
                 , UPD_USER_ID = 'NONMEMBER'
                 , UPD_DATE = NOW()
             WHERE BOARD_SEQ = #{board_seq}
        
        </delete>
        
        <select id="getBoardDetail" parameterType="com.spring.board.form.BoardForm" resultType="com.spring.board.dto.BoardDto">
        
            SELECT BOARD_SEQ 
                 , BOARD_RE_REF 
                 , BOARD_RE_LEV 
                 , BOARD_RE_SEQ 
                 , BOARD_WRITER 
                 , BOARD_SUBJECT 
                 , BOARD_CONTENT 
                 , BOARD_HITS
                 , DEL_YN 
                 , INS_USER_ID
                 , CAST( DATE_FORMAT( INS_DATE, '%Y-%m-%d %H:%i:%s' ) AS CHAR(19) ) AS INS_DATE
                 , UPD_USER_ID
                 , CAST( DATE_FORMAT( UPD_DATE, '%Y-%m-%d %H:%i:%s' ) AS CHAR(19) ) AS UPD_DATE  
            FROM BOARD.TB_BOARD
            WHERE BOARD_SEQ = #{board_seq}
        
        </select>
            
        <select id="getBoardFileList" parameterType="com.spring.board.form.BoardFileForm" resultType="com.spring.board.dto.BoardFileDto">
        
            SELECT T1.*
            FROM (
                    SELECT BOARD_SEQ
                         , FILE_NO
                         , FILE_NAME_KEY
                         , FILE_NAME
                         , FILE_PATH
                         , FILE_SIZE
                         , REMARK
                         , INS_USER_ID
                         , CAST( DATE_FORMAT( INS_DATE, '%Y-%m-%d %H:%i:%s' ) AS CHAR(19) ) AS INS_DATE
                         , UPD_USER_ID
                         , CAST( DATE_FORMAT( UPD_DATE, '%Y-%m-%d %H:%i:%s' ) AS CHAR(19) ) AS UPD_DATE
                    FROM BOARD.TB_BOARD_FILE
                    WHERE BOARD_SEQ = #{board_seq}
                    AND DEL_YN = 'N'
                  ) T1        
                
        </select>
        
        <select id="getBoardReRef" parameterType="com.spring.board.form.BoardForm" resultType="int">
        
            SELECT IFNULL(MAX(BOARD_RE_REF), 0) + 1
            FROM BOARD.TB_BOARD
        
        </select>
        
        <insert id="insertBoard" parameterType="com.spring.board.form.BoardForm">
            
            <selectKey resultType="int" keyProperty="board_seq" order="AFTER">
     
                SELECT LAST_INSERT_ID()
     
            </selectKey>
            
            INSERT 
            INTO BOARD.TB_BOARD 
            (
                    BOARD_RE_REF
                  , BOARD_RE_LEV
                  , BOARD_RE_SEQ
                  , BOARD_WRITER
                  , BOARD_SUBJECT
                  , BOARD_CONTENT
                  , INS_USER_ID
                  , INS_DATE
                  , UPD_USER_ID
                  , UPD_DATE
            ) 
            VALUES 
            (
                  #{board_re_ref}
                 , 0
                 , 0
                 , #{board_writer}
                 , #{board_subject}
                 , #{board_content}
                 , 'NONMEMBER'
                 , NOW() 
                 , 'NONMEMBER'
                 , NOW() 
            )
                
        </insert>
        
        <insert id="insertBoardFile" parameterType="com.spring.board.form.BoardFileForm">
        
            <selectKey resultType="int" keyProperty="file_no" order="BEFORE">
                
                SELECT IFNULL(MAX(FILE_NO), 0) + 1 
                FROM BOARD.TB_BOARD_FILE
                WHERE BOARD_SEQ = #{board_seq}
                  
            </selectKey>
                    
            INSERT 
            INTO TB_BOARD_FILE
            (
                  BOARD_SEQ
                , FILE_NO
                , FILE_NAME_KEY
                , FILE_NAME
                , FILE_PATH
                , FILE_SIZE
                , DEL_YN 
                , INS_USER_ID
                , INS_DATE            
                , UPD_USER_ID
                , UPD_DATE
            )
            VALUES
            (
                  #{board_seq}
                , #{file_no}
                , #{file_name_key}
                , #{file_name}
                , #{file_path}
                , #{file_size}
                , 'N'
                , 'NONMEMBER'
                , NOW() 
                , 'NONMEMBER'
                , NOW() 
            )    
            
        </insert>
        
        <insert id="insertBoardFail" parameterType="com.spring.board.form.BoardForm">
        
            INSERT 
            INTO BOARD.TB_BOARD 
            (
                    BOARD_RE_REF
                  , BOARD_RE_LEV
                  , BOARD_RE_SEQ
                  , BOARD_WRITER
                  , BOARD_SUBJECT
                  , BOARD_CONTENT
                  , INS_USER_ID
                  , INS_DATE
                  , UPD_USER_ID
                  , UPD_DATE
            ) 
            VALUES 
            (
                   0
                 , 0
                 , 0
                 , #{board_writer1}
                 , #{board_subject}
                 , #{board_content}
                 , 'NONMEMBER'
                 , NOW() 
                 , 'NONMEMBER'
                 , NOW() 
            )
        
        </insert>
            
        <delete id="deleteBoard" parameterType="com.spring.board.form.BoardForm">
        
            DELETE 
            FROM BOARD.TB_BOARD 
            WHERE BOARD_SEQ = #{board_seq}
        
        </delete>
        
        <delete id="updateBoard" parameterType="com.spring.board.form.BoardForm">
        
            UPDATE BOARD.TB_BOARD 
               SET BOARD_SUBJECT = #{board_subject}
                 , BOARD_CONTENT = #{board_content}
                 , UPD_USER_ID = 'NONMEMBER'
                 , UPD_DATE = NOW()
             WHERE BOARD_SEQ = #{board_seq}
        
        </delete>
        
        <select id="getBoardReplyInfo" parameterType="com.spring.board.form.BoardForm" resultType="com.spring.board.dto.BoardDto">
        
            SELECT BOARD_SEQ
                 , BOARD_RE_REF
                 , BOARD_RE_LEV
                 , BOARD_RE_SEQ
            FROM TB_BOARD
            WHERE BOARD_SEQ = #{board_parent_seq}
        
        </select>
        
        <delete id="updateBoardReSeq" parameterType="com.spring.board.form.BoardForm">
        
            UPDATE TB_BOARD
               SET BOARD_RE_SEQ = BOARD_RE_SEQ + 1
                 , UPD_USER_ID = 'NONMEMBER'
                 , UPD_DATE = NOW()
             WHERE BOARD_RE_REF = #{board_re_ref} 
               AND BOARD_RE_SEQ > #{board_re_seq}
        
        </delete>
        
        <insert id="insertBoardReply" parameterType="com.spring.board.form.BoardForm">
        
            INSERT 
            INTO BOARD.TB_BOARD 
            (
                    BOARD_RE_REF
                  , BOARD_RE_LEV
                  , BOARD_RE_SEQ
                  , BOARD_WRITER
                  , BOARD_SUBJECT
                  , BOARD_CONTENT
                  , INS_USER_ID
                  , INS_DATE
                  , UPD_USER_ID
                  , UPD_DATE
            ) 
            VALUES 
            (
                   #{board_re_ref}
                 , #{board_re_lev} + 1
                 , #{board_re_seq} + 1
                 , #{board_writer}
                 , #{board_subject}
                 , #{board_content}
                 , 'NONMEMBER'
                 , NOW() 
                 , 'NONMEMBER'
                 , NOW() 
            )
        
        </insert>
        
           <delete id="deleteBoardFile" parameterType="com.spring.board.form.BoardFileForm">
        
            UPDATE BOARD.TB_BOARD_FILE 
               SET DEL_YN = 'Y'
                 , UPD_USER_ID = 'NONMEMBER'
                 , UPD_DATE = NOW()
             WHERE BOARD_SEQ = #{board_seq}
               AND FILE_NO = #{file_no}
        
        </delete>
        
    </mapper>
    cs

     

    3. 게시글 상세 화면에서 첨부파일이 등록 및 삭제되는지 확인하세요.

     

    소스 코드는 Github Repository - https://github.com/tychejin1218/board_v1 (branch : section21) 를 참조하세요.
    Github에서 프로젝트 가져오기 - https://tychejin.tistory.com/33

     
     

     

    반응형

    댓글

Designed by Tistory.