본문 바로가기
Java/└ [Servlet & JSP] Practice

[실습문제] 첨부파일 없는 게시글 수정

by 박채니 2022. 7. 5.

안녕하세요, 코린이의 코딩 학습기 채니 입니다.

 

개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.


@실습문제

- 첨부파일이 없는 게시글 수정 (파일 업로드 구현)

 

boardUpdate.jsp

<%@page import="com.ce.mvc2.board.model.dto.Board"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/views/common/header.jsp" %>    
<%
	Board board = (Board)request.getAttribute("board");
	
%>
<link rel="stylesheet" href="<%=request.getContextPath()%>/css/board.css" />

<section id="board-container">
<h2>게시판 수정</h2>
<form name="boardUpdateFrm" action="<%=request.getContextPath() %>/board/boardUpdate" method="post" enctype="multipart/form-data">
	<input type="hidden" name="no" value="<%= board.getNo() %>" />
	<table id="tbl-board-view">
	<tr>
		<th>제 목</th>
		<td><input type="text" name="title" value="<%= board.getTitle() %>" required></td>
	</tr>
	<tr>
		<th>작성자</th>
		<td>
			<input type="text" name="writer" value="<%= board.getWriter() %>" readonly/>
		</td>
	</tr>
	<tr>
		<th>첨부파일</th>
		<td >
			<input type="file" name="upFile1">
			<input type="file" name="upFile2">
		</td>
	</tr>
	<tr>
		<th>내 용</th>
		<td><textarea rows="5" cols="40" name="content"><%= board.getContent() %></textarea></td>
	</tr>
	<tr>
		<th colspan="2">
			<input type="submit" value="수정하기"/>
			<input type="button" value="취소" onclick="history.go(-1);"/>
		</th>
	</tr>
</table>
</form>
</section>
<script>
document.boardUpdateFrm.onsubmit = (e) => {
	const frm = e.target;
	//제목을 작성하지 않은 경우 폼제출할 수 없음.
	const titleVal = frm.title.value.trim(); // 좌우공백
	if(!/^.+$/.test(titleVal)){
		alert("제목을 작성해주세요.");
		frm.title.select();
		return false;
	}		
					   
	//내용을 작성하지 않은 경우 폼제출할 수 없음.
	const contentVal = frm.content.value.trim();
	if(!/^(.|\n)+$/.test(contentVal)){
		alert("내용을 작성해주세요.");
		frm.content.select();
		return false;
	}
}
</script>
<%@ include file="/WEB-INF/views/common/footer.jsp" %>

 

Controller

BoardUpdateServlet

@WebServlet("/board/boardUpdate")
public class BoardUpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BoardService boardService = new BoardService();
	
	/**
	 * GET 수정폼요청
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			int no = Integer.parseInt(request.getParameter("no"));
			Board board = boardService.findByNo(no);
			request.setAttribute("board", board);
			request.getRequestDispatcher("/WEB-INF/views/board/boardUpdate.jsp").forward(request, response);
		} catch(Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * POST db update 요청
	 * - 파일업로드 가능성있음
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			// 첨부파일 처리
			// saveDirectory, maxPostSize, encoding, policy
			ServletContext application = getServletContext();
			String saveDirectory = application.getRealPath("/upload/board");
			int maxPostSize = 1024 * 1024 * 10; // 10MB
			String encoding = "utf-8";
			FileRenamePolicy policy = new HelloMvcFileRenamePolicy();
			MultipartRequest multiReq = new MultipartRequest(request, saveDirectory, maxPostSize, encoding, policy);
			
			// 사용자 입력값 처리
			int no = Integer.parseInt(multiReq.getParameter("no"));
			String title = multiReq.getParameter("title");
			String writer = multiReq.getParameter("writer");
			String content = multiReq.getParameter("content");
			BoardExt board = new BoardExt(no, title, writer, content, 0, null);
			
			Enumeration<String> filenames = multiReq.getFileNames();
			while(filenames.hasMoreElements()) {
				String filename = filenames.nextElement();
				File upFile = multiReq.getFile(filename);
				
				if(upFile != null) {
					Attachment attach = new Attachment();
					attach.setBoardNo(no);
					attach.setOriginalFilename(multiReq.getOriginalFileName(filename));
					attach.setRenamedFilename(multiReq.getFilesystemName(filename));
					board.addAttachment(attach);
				}
			}
			
			// 업무로직
			int result = boardService.updateBoard(board);
			
			// redirect 처리
			request.getSession().setAttribute("msg", "게시글을 성공적으로 수정하였습니다.");
			response.sendRedirect(request.getContextPath() + "/board/boardView?no=" + no);
		} catch(Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
}

 

Service

BoardService

public int updateBoard(BoardExt board) {
    Connection conn = getConnection();
    int result = 0;
    try {
        result = boardDao.updateBoard(conn, board);

        if(board.getAttachments() != null || !board.getAttachments().isEmpty()) {
            for(Attachment attach : board.getAttachments()) {
                result = boardDao.insertAttachment(conn, attach);
            }
        }
        commit(conn);
    } catch(Exception e) {
        rollback(conn);
        throw e;
    } finally {
        close(conn);
    }
    return result;
}

 

Dao

BoardDao

// updateBoard = update board set title = ?, content = ? where no = ?
public int updateBoard(Connection conn, BoardExt board) {
    PreparedStatement pstmt = null;
    int result = 0;
    String sql = prop.getProperty("updateBoard");

    try {
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, board.getTitle());
        pstmt.setString(2, board.getContent());
        pstmt.setInt(3, board.getNo());
        result = pstmt.executeUpdate();
    } catch (SQLException e) {
        throw new BoardException("게시글 수정 오류!", e);
    } finally {
        close(pstmt);
    }
    return result;
}

 

'Java > └ [Servlet & JSP] Practice' 카테고리의 다른 글

[실습문제] 게시글 등록  (0) 2022.07.02
[실습문제] 회원 정보 수정  (0) 2022.06.26
[실습문제] 내 정보 보기  (0) 2022.06.25