본문 바로가기
Java/Servlet & JSP

JSP) 게시글 상세보기 - 게시글 수정/삭제 권한에 따라 버튼 노출하기

by 박채니 2022. 7. 3.

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

 

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


게시글 상세보기

 

boarList.jsp

a 링크 걸기

<%
	List<Board> boardList = (List<Board>)request.getAttribute("boardList");
%>
<link rel="stylesheet" href="<%=request.getContextPath()%>/css/board.css" />
<section id="board-container">
	<h2>게시판 </h2>
	<% if(loginMember != null) { %>
		<input type="button" value="글쓰기" id="btn-add" onclick="location.href='<%=request.getContextPath() %>/board/boardEnroll';" />
	<% } %>
	<table id="tbl-board">
		<tr>
			<th>번호</th>
			<th>제목</th>
			<th>작성자</th>
			<th>작성일</th>
			<th>첨부파일</th><%--첨부파일이 있는 경우 /images/file.png 표시 width:16px --%>
			<th>조회수</th>
		</tr>
		<% if(boardList != null && !boardList.isEmpty()) { 
			for(Board board : boardList) { 
				BoardExt boardExt = (BoardExt)board;	
		%>
		<tr>
			<td><%= board.getNo() %></td>
			<td>
				<a href="<%= request.getContextPath()%>/board/boardView?no=<%=board.getNo() %>"><%= board.getTitle() %></a>
			</td>
			<td><%= board.getWriter() %></td>
			<td><%= new SimpleDateFormat("yyyy-MM-dd HH:mm").format(board.getRegDate()) %></td>
			<td>
				<% if(boardExt.getAttachCount() > 0) { %>
					<img src="<%=request.getContextPath() %>/images/file.png" alt="" width="16px"/>
				<% } %>
			</td>
			<td><%= board.getReadCount() %></td>
		</tr>
		<% 	}
		} else { %>
		<tr>
			<td colspan="6">조회된 게시글이 없습니다.</td>
		</tr>
		<% } %>
	</table>
	
	<div id='pagebar'>
		<%= request.getAttribute("pagebar") %>
	</div>
</section>
<%@ include file="/WEB-INF/views/common/footer.jsp" %>

어떤 게시글을 보는 지 알기 위해 /board/boardView?no=<%=board.getNo()%>로 넘겨주었기 때문에 boardViewServlet에서도 no를 가져와 사용할 수 있습니다.

 

Controller

BoardViewServlet

@WebServlet("/board/boardView")
public class BoardViewServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BoardService boardService = new BoardService();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			// 1. 사용자입력값 처리
			int no = Integer.parseInt(request.getParameter("no"));
			
			// 2. 업무로직 
			Board board = boardService.findByNo(no);
            
			// 개행문자 변환처리
			board.setContent(HelloMvcUtils.convertLineBeedToBr(board.getContent()));
            
			// 3. view단 처리
			request.setAttribute("board", board);
			request.getRequestDispatcher("/WEB-INF/views/board/boardView.jsp").forward(request, response);
		} catch(Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
}

 

HelloMvcUtils

convertLineBeedToBr()

public static String convertLineBeedToBr(String str) {
    return str.replaceAll("\\n", "<br>");
}

개행문자 처리를 위해 위와 같은 메소드를 만들었습니다.

 

Service

BoardService

public Board findByNo(int no) {
    Connection conn = getConnection();
    // board 테이블에서 조회
    Board board = boardDao.findByNo(conn, no);

    // attachment 테이블에서 조회
    List<Attachment> attachments = boardDao.findAttachmentByNo(conn, no);
    ((BoardExt) board).setAttachments(attachments);

    close(conn);
    return board;
}

게시글, 첨부파일 모두 가져와야 하기 때문에 하나의 Connection에서 board와 attachment 테이블을 조회하였습니다.

게시글 번호를 넘겨 받았으므로 해당 게시글 번호를 가지고 attachment테이블에서도 조회할 수 있습니다.

조회하여 가져온 첨부파일들을 boardExt의 Attachments에 담아주고 리턴해줍니다.

 

Dao

BoardDao

// findByNo = select * from board where no = ?
public Board findByNo(Connection conn, int no) {
    PreparedStatement pstmt = null;
    ResultSet rset = null;
    Board board = null;
    String sql = prop.getProperty("findByNo");

    try {
        pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, no);
        rset = pstmt.executeQuery();
        while(rset.next()) {
            board = handleBoardResultSet(rset);
        }
    } catch (SQLException e) {
        throw new BoardException("게시글 1건 조회 오류", e);
    } finally {
        close(rset);
        close(pstmt);
    }
    return board;
}

// findAttachmentByNo = select * from attachment where board_no = ?
public List<Attachment> findAttachmentByNo(Connection conn, int boardNo) {
    PreparedStatement pstmt = null;
    ResultSet rset = null;
    List<Attachment> attachments = new ArrayList<>();
    String sql = prop.getProperty("findAttachmentByNo");

    try {
        pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, boardNo);
        rset = pstmt.executeQuery();
        while(rset.next()) {
            attachments.add(handleAttachmentResultSet(rset));
        }
    } catch (SQLException e) {
        throw new BoardException("게시글 별 첨부파일 조회 오류!", e);
    } finally {
        close(rset);
        close(pstmt);
    }
    return attachments;
}

private Attachment handleAttachmentResultSet(ResultSet rset) throws SQLException {
    Attachment attachment = new Attachment();
    attachment.setNo(rset.getInt("no"));
    attachment.setBoardNo(rset.getInt("board_no"));
    attachment.setOriginalFilename(rset.getString("original_filename"));
    attachment.setRenamedFilename(rset.getString("renamed_filename"));
    attachment.setRegDate(rset.getTimestamp("reg_date"));
    return attachment;
}

 

boardView.jsp

<%@page import="com.ce.mvc2.board.model.dto.BoardExt"%>
<%@page import="com.ce.mvc2.board.model.dto.Attachment"%>
<%@page import="java.util.List"%>
<%@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");
	List<Attachment> attachments = ((BoardExt) board).getAttachments();
%>
<link rel="stylesheet" href="<%=request.getContextPath()%>/css/board.css" />
<section id="board-container">
	<h2>게시판</h2>
	<table id="tbl-board-view">
		<tr>
			<th>글번호</th>
			<td><%= board.getNo() %></td>
		</tr>
		<tr>
			<th>제 목</th>
			<td><%= board.getTitle() %></td>
		</tr>
		<tr>
			<th>작성자</th>
			<td><%= board.getWriter() %></td>
		</tr>
		<tr>
			<th>조회수</th>
			<td></td>
		</tr>
			<% if(attachments != null && !attachments.isEmpty()) {
				for(Attachment attach : attachments) { %>
		<tr>
			<th>첨부파일</th>
			<td>
				<%-- 첨부파일이 있을경우만, 이미지와 함께 original파일명 표시 --%>
				<img alt="첨부파일" src="<%=request.getContextPath() %>/images/file.png" width=16px>
				<a href="#"><%= attach.getOriginalFilename() %></a>
			</td>
		</tr>
			<% 	}
			} %>
		<tr>
			<th>내 용</th>
			<td><%= board.getContent() %></td>
		</tr>
		<% 
		boolean canEdit = loginMember != null && (loginMember.getMemberId().equals(board.getWriter()) || loginMember.getMemberRole() == MemberRole.A);
		if(canEdit) { %>
		<tr>
			<%-- 작성자와 관리자만 마지막행 수정/삭제버튼이 보일수 있게 할 것 --%>
			<th colspan="2">
				<input type="button" value="수정하기" onclick="updateBoard()">
				<input type="button" value="삭제하기" onclick="deleteBoard()">
			</th>
		</tr>
		<% } %>
	</table>
</section>
<%@ include file="/WEB-INF/views/common/footer.jsp" %>

게시글 상세조회 시 게시글 내용과 첨부파일도 확인할 수 있으며, 게시글 작성자/관리자에게서만 수정하기/삭제하기 버튼이 확인되도록 구현하였습니다.