1. 개요
■ 지난 포스팅 : [JSP개발] 게시판 - 글목록 및 검색 구현
이번에는 글 목록에서 제목을 클릭 시 글 상세보기와 글에 첨부된 파일을 다운로드하는 것을 구현할 것이다. 추가 및 수정할 JSP와 Java는 위와 같다.
■ JSP
BoardDetailForm.jsp : 글의 상세보기 페이지이다.
BoardListForm.jsp : 글 목록을 보여주는 JSP이다. 일부 수정된 부분이 있다.
■ Java
BoardDAO.java : 상세보기와 조회수 증가를 위한 메서드를 추가하였다.
BoardDetailAction.java : 상세보기를 처리하는 Action이다.
FileDownloadAction.java : 파일 다운로드를 처리하는 Action이다.
2. 소스 코드
■ BoardListForm.jsp
지난 포스팅에서는 위에 표시된 부분의 &pageNum=${pageNum} 으로 되어있다. 이것을 &pageNum=${spage}로 수정하였다. 이 부분은 글 목록에서 글 제목을 클릭할 경우 상세보기 페이지로 이동시키는 부분이다.
여기서 글 번호와 페이지 번호를 넘기는데 글 번호는 이것으로 해당 글의 정보를 가져올 것이고, 페이지 번호는 상세보기에서 목록으로 돌아갈 경우 기존 페이지로 이동하기 위해서 필요하다.
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 | <%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <title>전체 게시글</title> <style type="text/css"> #wrap { width: 800px; margin: 0 auto 0 auto; } #topForm{ text-align :right; } #board, #pageForm, #searchForm{ text-align :center; } #bList{ text-align :center; } </style> <script type="text/javascript"> function writeForm(){ location.href="BoardWriteForm.bo"; } </script> </head> <body> <div id="wrap"> <!-- 글목록 위 부분--> <br> <div id="topForm"> <c:if test="${sessionScope.sessionID!=null}"> <input type="button" value="글쓰기" onclick="writeForm()"> </c:if> </div> <!-- 게시글 목록 부분 --> <br> <div id="board"> <table id="bList" width="800" border="3" bordercolor="lightgray"> <tr heigh="30"> <td>글번호</td> <td>제목</td> <td>작성자</td> <td>작성일</td> <td>조회수</td> </tr> <c:forEach var="board" items="${requestScope.list}"> <tr> <td>${board.board_num}</td> <td> <a href="BoardDetailAction.bo?num=${board.board_num}&pageNum=${spage}"> ${board.board_subject} </a> </td> <td> <a href="#"> ${board.board_id} </a> </td> <td>${board.board_date}</td> <td>${board.board_count}</td> </tr> </c:forEach> </table> </div> <!-- 페이지 넘버 부분 --> <br> <div id="pageForm"> <c:if test="${startPage != 1}"> <a href='BoardListAction.bo?page=${startPage-1}'>[ 이전 ]</a> </c:if> <c:forEach var="pageNum" begin="${startPage}" end="${endPage}"> <c:if test="${pageNum == spage}"> ${pageNum} </c:if> <c:if test="${pageNum != spage}"> <a href='BoardListAction.bo?page=${pageNum}'>${pageNum} </a> </c:if> </c:forEach> <c:if test="${endPage != maxPage }"> <a href='BoardListAction.bo?page=${endPage+1 }'>[다음]</a> </c:if> </div> <!-- 검색 부분 --> <br> <div id="searchForm"> <form> <select name="opt"> <option value="0">제목</option> <option value="1">내용</option> <option value="2">제목+내용</option> <option value="3">글쓴이</option> </select> <input type="text" size="20" name="condition"/> <input type="submit" value="검색"/> </form> </div> </div> </body> </html> | cs |
■ BoardDAO.java
DAO에서는 글 번호를 이용해 해당 글을 찾고, 조회 수를 증가시키는 메서드를 추가한다.
getDetail( )은 글 번호를 인자로 넘겨받아 그에 해당하는 글을 찾는다. 그리고 그 정보를 BoardBean에 담아 리턴한다.
updateCount( )는 글의 조회 수를 증가시킨다. 상세보기 한 글의 글 번호를 넘겨받아서 해당 글의 조회 수를 1 증가시킨다.
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 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 | package jsp.board.model; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import jsp.common.util.DBConnection; public class BoardDAO { private Connection conn; private PreparedStatement pstmt; private ResultSet rs; private static BoardDAO instance; private BoardDAO(){} public static BoardDAO getInstance(){ if(instance==null) instance=new BoardDAO(); return instance; } // 시퀀스를 가져온다. public int getSeq() { int result = 1; try { conn = DBConnection.getConnection(); // 시퀀스 값을 가져온다. (DUAL : 시퀀스 값을 가져오기위한 임시 테이블) StringBuffer sql = new StringBuffer(); sql.append("SELECT BOARD_NUM.NEXTVAL FROM DUAL"); pstmt = conn.prepareStatement(sql.toString()); // 쿼리 실행 rs = pstmt.executeQuery(); if(rs.next()) result = rs.getInt(1); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } close(); return result; } // end getSeq // 글 삽입 public boolean boardInsert(BoardBean board) { boolean result = false; try { conn = DBConnection.getConnection(); // 자동 커밋을 false로 한다. conn.setAutoCommit(false); StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO MEMBER_BOARD"); sql.append("(BOARD_NUM, BOARD_ID, BOARD_SUBJECT, BOARD_CONTENT, BOARD_FILE"); sql.append(", BOARD_RE_REF, BOARD_RE_LEV, BOARD_RE_SEQ, BOARD_COUNT, BOARD_DATE)"); sql.append(" VALUES(?,?,?,?,?,?,?,?,?,sysdate)"); // 시퀀스 값을 글번호와 그룹번호로 사용 int num = board.getBoard_num(); pstmt = conn.prepareStatement(sql.toString()); pstmt.setInt(1, num); pstmt.setString(2, board.getBoard_id()); pstmt.setString(3, board.getBoard_subject()); pstmt.setString(4, board.getBoard_content()); pstmt.setString(5, board.getBoard_file()); pstmt.setInt(6, num); pstmt.setInt(7, 0); pstmt.setInt(8, 0); pstmt.setInt(9, 0); int flag = pstmt.executeUpdate(); if(flag > 0){ result = true; // 완료시 커밋 conn.commit(); } } catch (Exception e) { try { conn.rollback(); } catch (SQLException sqle) { sqle.printStackTrace(); } throw new RuntimeException(e.getMessage()); } close(); return result; } // end boardInsert(); // 글목록 가져오기 public ArrayList<BoardBean> getBoardList(HashMap<String, Object> listOpt) { ArrayList<BoardBean> list = new ArrayList<BoardBean>(); String opt = (String)listOpt.get("opt"); String condition = (String)listOpt.get("condition"); int start = (Integer)listOpt.get("start"); try { conn = DBConnection.getConnection(); StringBuffer sql = new StringBuffer(); // 글목록 전체를 보여줄 때 if(opt == null) { // BOARD_RE_REF(그룹번호)의 내림차순 정렬 후 동일한 그룹번호일 때는 // BOARD_RE_SEQ(답변글 순서)의 오름차순으로 정렬 한 후에 // start번 째 부터 start+9까지(10개의 글을 한 목록에 보여주기 위해)의 // 데이터를 검색해주는 sql // desc : 내림차순, asc : 오름차순 ( 생략 가능 ) sql.append("select * from "); sql.append("(select rownum rnum, BOARD_NUM, BOARD_ID, BOARD_SUBJECT"); sql.append(", BOARD_CONTENT, BOARD_FILE, BOARD_COUNT, BOARD_RE_REF"); sql.append(", BOARD_RE_LEV, BOARD_RE_SEQ, BOARD_DATE "); sql.append("FROM"); sql.append(" (select * from MEMBER_BOARD order by BOARD_RE_REF desc, BOARD_RE_SEQ asc)) "); sql.append("where rnum>=? and rnum<=?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setInt(1, start); pstmt.setInt(2, start+9); // StringBuffer를 비운다. sql.delete(0, sql.toString().length()); } else if(opt.equals("0")) // 제목으로 검색 { sql.append("select * from "); sql.append("(select rownum rnum, BOARD_NUM, BOARD_ID, BOARD_SUBJECT"); sql.append(", BOARD_CONTENT, BOARD_FILE, BOARD_DATE, BOARD_COUNT"); sql.append(", BOARD_RE_REF, BOARD_RE_LEV, BOARD_RE_SEQ "); sql.append("FROM "); sql.append("(select * from MEMBER_BOARD where BOARD_SUBJECT like ? "); sql.append("order BY BOARD_RE_REF desc, BOARD_RE_SEQ asc)) "); sql.append("where rnum>=? and rnum<=?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, "%"+condition+"%"); pstmt.setInt(2, start); pstmt.setInt(3, start+9); sql.delete(0, sql.toString().length()); } else if(opt.equals("1")) // 내용으로 검색 { sql.append("select * from "); sql.append("(select rownum rnum, BOARD_NUM, BOARD_ID, BOARD_SUBJECT"); sql.append(", BOARD_CONTENT, BOARD_FILE, BOARD_DATE, BOARD_COUNT"); sql.append(", BOARD_RE_REF, BOARD_RE_LEV, BOARD_RE_SEQ "); sql.append("FROM "); sql.append("(select * from MEMBER_BOARD where BOARD_CONTENT like ? "); sql.append("order BY BOARD_RE_REF desc, BOARD_RE_SEQ asc)) "); sql.append("where rnum>=? and rnum<=?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, "%"+condition+"%"); pstmt.setInt(2, start); pstmt.setInt(3, start+9); sql.delete(0, sql.toString().length()); } else if(opt.equals("2")) // 제목+내용으로 검색 { sql.append("select * from "); sql.append("(select rownum rnum, BOARD_NUM, BOARD_ID, BOARD_SUBJECT"); sql.append(", BOARD_CONTENT, BOARD_FILE, BOARD_DATE, BOARD_COUNT"); sql.append(", BOARD_RE_REF, BOARD_RE_LEV, BOARD_RE_SEQ "); sql.append("FROM "); sql.append("(select * from MEMBER_BOARD where BOARD_SUBJECT like ? OR BOARD_CONTENT like ? "); sql.append("order BY BOARD_RE_REF desc, BOARD_RE_SEQ asc)) "); sql.append("where rnum>=? and rnum<=?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, "%"+condition+"%"); pstmt.setString(2, "%"+condition+"%"); pstmt.setInt(3, start); pstmt.setInt(4, start+9); sql.delete(0, sql.toString().length()); } else if(opt.equals("3")) // 글쓴이로 검색 { sql.append("select * from "); sql.append("(select rownum rnum, BOARD_NUM, BOARD_ID, BOARD_SUBJECT"); sql.append(", BOARD_CONTENT, BOARD_FILE, BOARD_DATE, BOARD_COUNT"); sql.append(", BOARD_RE_REF, BOARD_RE_LEV, BOARD_RE_SEQ "); sql.append("FROM "); sql.append("(select * from MEMBER_BOARD where BOARD_ID like ? "); sql.append("order BY BOARD_RE_REF desc, BOARD_RE_SEQ asc)) "); sql.append("where rnum>=? and rnum<=?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, "%"+condition+"%"); pstmt.setInt(2, start); pstmt.setInt(3, start+9); sql.delete(0, sql.toString().length()); } rs = pstmt.executeQuery(); while(rs.next()) { BoardBean board = new BoardBean(); board.setBoard_num(rs.getInt("BOARD_NUM")); board.setBoard_id(rs.getString("BOARD_ID")); board.setBoard_subject(rs.getString("BOARD_SUBJECT")); board.setBoard_content(rs.getString("BOARD_CONTENT")); board.setBoard_file(rs.getString("BOARD_FILE")); board.setBoard_count(rs.getInt("BOARD_COUNT")); board.setBoard_re_ref(rs.getInt("BOARD_RE_REF")); board.setBoard_re_lev(rs.getInt("BOARD_RE_LEV")); board.setBoard_re_seq(rs.getInt("BOARD_RE_SEQ")); board.setBoard_date(rs.getDate("BOARD_DATE")); list.add(board); } } catch (Exception e) { throw new RuntimeException(e.getMessage()); } close(); return list; } // end getBoardList // 글의 개수를 가져오는 메서드 public int getBoardListCount(HashMap<String, Object> listOpt) { int result = 0; String opt = (String)listOpt.get("opt"); String condition = (String)listOpt.get("condition"); try { conn = DBConnection.getConnection(); StringBuffer sql = new StringBuffer(); if(opt == null) // 전체글의 개수 { sql.append("select count(*) from MEMBER_BOARD"); pstmt = conn.prepareStatement(sql.toString()); // StringBuffer를 비운다. sql.delete(0, sql.toString().length()); } else if(opt.equals("0")) // 제목으로 검색한 글의 개수 { sql.append("select count(*) from MEMBER_BOARD where BOARD_SUBJECT like ?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, '%'+condition+'%'); sql.delete(0, sql.toString().length()); } else if(opt.equals("1")) // 내용으로 검색한 글의 개수 { sql.append("select count(*) from MEMBER_BOARD where BOARD_CONTENT like ?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, '%'+condition+'%'); sql.delete(0, sql.toString().length()); } else if(opt.equals("2")) // 제목+내용으로 검색한 글의 개수 { sql.append("select count(*) from MEMBER_BOARD "); sql.append("where BOARD_SUBJECT like ? or BOARD_CONTENT like ?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, '%'+condition+'%'); pstmt.setString(2, '%'+condition+'%'); sql.delete(0, sql.toString().length()); } else if(opt.equals("3")) // 글쓴이로 검색한 글의 개수 { sql.append("select count(*) from MEMBER_BOARD where BOARD_ID like ?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, '%'+condition+'%'); sql.delete(0, sql.toString().length()); } rs = pstmt.executeQuery(); if(rs.next()) result = rs.getInt(1); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } close(); return result; } // end getBoardListCount // 상세보기 public BoardBean getDetail(int boardNum) { BoardBean board = null; try { conn = DBConnection.getConnection(); StringBuffer sql = new StringBuffer(); sql.append("select * from MEMBER_BOARD where BOARD_NUM = ?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setInt(1, boardNum); rs = pstmt.executeQuery(); if(rs.next()) { board = new BoardBean(); board.setBoard_num(boardNum); board.setBoard_id(rs.getString("BOARD_ID")); board.setBoard_subject(rs.getString("BOARD_SUBJECT")); board.setBoard_content(rs.getString("BOARD_CONTENT")); board.setBoard_file(rs.getString("BOARD_FILE")); board.setBoard_count(rs.getInt("BOARD_COUNT")); board.setBoard_re_ref(rs.getInt("BOARD_RE_REF")); board.setBoard_re_lev(rs.getInt("BOARD_RE_LEV")); board.setBoard_re_seq(rs.getInt("BOARD_RE_SEQ")); board.setBoard_date(rs.getDate("BOARD_DATE")); } } catch (Exception e) { throw new RuntimeException(e.getMessage()); } close(); return board; } // end getDetail() // 조회수 증가 public boolean updateCount(int boardNum) { boolean result = false; try { conn = DBConnection.getConnection(); StringBuffer sql = new StringBuffer(); sql.append("update MEMBER_BOARD set BOARD_COUNT = BOARD_COUNT+1 "); sql.append("where BOARD_NUM = ?"); pstmt = conn.prepareStatement(sql.toString()); pstmt.setInt(1, boardNum); int flag = pstmt.executeUpdate(); if(flag > 0){ result = true; conn.commit(); // 완료시 커밋 } } catch (Exception e) { try { conn.rollback(); // 오류시 롤백 } catch (SQLException sqle) { sqle.printStackTrace(); } throw new RuntimeException(e.getMessage()); } close(); return result; } // end updateCount // DB 자원해제 private void close() { try { if ( pstmt != null ){ pstmt.close(); pstmt=null; } if ( conn != null ){ conn.close(); conn=null; } } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } // end close() } | cs |
■ BoardDetailAction.java
BoardDetailAction에서는 BoardListForm.jsp(글 목록 화면)에서 넘겨받은 글 번호와 페이지 번호를 가져온다. 그리고 이것을 이용해서 해당 글을 찾고 조회 수를 증가시킨다.
그리고 가져온 글의 정보와 페이지 번호를 request에 세팅한다. 페이지 번호의 경우 상세보기 화면에서 다시 글 목록으로 돌아갈 때 기존에 있던 페이지로 돌아가야 하기 때문에 request를 통해 전달한다.
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 | package jsp.board.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import jsp.board.model.BoardBean; import jsp.board.model.BoardDAO; import jsp.common.action.Action; import jsp.common.action.ActionForward; public class BoardDetailAction implements Action { @Override public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = new ActionForward(); // 파라미터로 넘어온 글번호를 가져온다. String num = request.getParameter("num"); int boardNum = Integer.parseInt(num); String pageNum = request.getParameter("pageNum"); BoardDAO dao = BoardDAO.getInstance(); BoardBean board = dao.getDetail(boardNum); boolean result = dao.updateCount(boardNum); request.setAttribute("board", board); request.setAttribute("pageNum", pageNum); if(result){ forward.setRedirect(false); // 단순한 조회이므로 forward.setNextPath("BoardDetailForm.bo"); } return forward; } } | cs |
■ BoardDetailForm.jsp
상세보기 화면이다.
상세보기 화면에서는 첨부된 파일을 다운로드할 수 있게 되어있다. 첨부된 파일명을 클릭할 경우 FileDownloadAction이 실행되고 파일을 다운로드할 수 있다.
상세보기 하단의 버튼 중 목록 버튼을 클릭하면 다시 글 목록 화면으로 돌아간다.
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 | <%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <title>글 상세보기</title> <style type="text/css"> #wrap { width: 800px; margin: 0 auto 0 auto; } #detailBoard{ text-align :center; } #title{ height : 16; font-family :'돋움'; font-size : 12; text-align :center; } </style> </head> <body> <div id="wrap"> <br><br> <div id="board"> <table id="detailBoard" width="800" border="3" bordercolor="lightgray"> <tr> <td id="title">작성일</td> <td>${board.board_date}</td> </tr> <tr> <td id="title">작성자</td> <td>${board.board_id}</td> </tr> <tr> <td id="title"> 제 목 </td> <td> ${board.board_subject} </td> </tr> <tr> <td id="title"> 내 용 </td> <td> ${board.board_content} </td> </tr> <tr> <td id="title"> 첨부파일 </td> <td> <a href='FileDownloadAction.bo?file_name=${board.board_file}'>${board.board_file}</a> </td> </tr> <tr align="center" valign="middle"> <td colspan="5"> <input type="button" value="수정" > <input type="button" value="삭제" > <input type="button" value=답글 > <input type="button" value="목록" onclick="javascript:location.href='BoardListAction.bo?page=${pageNum}'"> </td> </tr> </table> </div> </div> </body> </html> | cs |
■ FileDownloadAction.java
첨부된 파일을 클릭할 경우 동작하는 Action이다. (파일 다운로드 처리)
상세보기 화면에서 전달한 파일명을 가져온다. 25줄에서는 파일이 저장된 폴더의 절대 경로를 가져온다. 27줄에서는 파일명과 절대 경로를 합쳐 파일이 있는 경로를 생성한다.
파일 경로를 이용하여 파일을 생성하고 파일의 크기만큼 바이트 배열을 만든다. 이후 response를 초기화 시키고 인코딩을 처리한다.
파일이 있을 경우 Stream 객체를 이용해서 파일을 출력한다.
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 | package jsp.board.action; import java.io.File; import java.io.FileInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import jsp.common.action.Action; import jsp.common.action.ActionForward; public class FileDownloadAction implements Action { @Override public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception { // 다운로드할 파일명을 가져온다. String fileName = request.getParameter("file_name"); // 파일이 있는 절대경로를 가져온다. // 현재 업로드된 파일은 UploadFolder 폴더에 있다. String folder = request.getServletContext().getRealPath("UploadFolder"); // 파일의 절대경로를 만든다. String filePath = folder + "/" + fileName; try { File file = new File(filePath); byte b[] = new byte[(int) file.length()]; // page의 ContentType등을 동적으로 바꾸기 위해 초기화시킴 response.reset(); response.setContentType("application/octet-stream"); // 한글 인코딩 String encoding = new String(fileName.getBytes("euc-kr"),"8859_1"); // 파일 링크를 클릭했을 때 다운로드 저장 화면이 출력되게 처리하는 부분 response.setHeader("Content-Disposition", "attachment;filename="+ encoding); response.setHeader("Content-Length", String.valueOf(file.length())); if (file.isFile()) // 파일이 있을경우 { FileInputStream fileInputStream = new FileInputStream(file); ServletOutputStream servletOutputStream = response.getOutputStream(); // 파일을 읽어서 클라이언트쪽으로 저장한다. int readNum = 0; while ( (readNum = fileInputStream.read(b)) != -1) { servletOutputStream.write(b, 0, readNum); } servletOutputStream.close(); fileInputStream.close(); } } catch (Exception e) { System.out.println("Download Exception : " + e.getMessage()); } return null; } } | cs |
■ BoardCommand.properties
상세보기 및 파일 다운로드에 해당하는 명령어를 등록한다.
1 2 3 4 5 6 7 8 9 10 | # Form Change BoardWriteForm.bo=jsp.board.action.BoardFormChangeAction BoardListForm.bo=jsp.board.action.BoardFormChangeAction BoardDetailForm.bo=jsp.board.action.BoardFormChangeAction # Action BoardWriteAction.bo=jsp.board.action.BoardWriteAction BoardListAction.bo=jsp.board.action.BoardListAction BoardDetailAction.bo=jsp.board.action.BoardDetailAction FileDownloadAction.bo=jsp.board.action.FileDownloadAction | cs |
3. 실행 결과
이클립스에서 클래스다이어그램 만들기(ObjectAid)를 클릭한다.
그러면 글의 상세 내용이 나타난다. 여기서 첨부된 파일을 클릭한다.
그러면 다운로드 화면이 나타난다.
4. 소스코드 다운로드 (war 파일)