본문 바로가기
Java/Servlet & JSP

JSP) 첨부파일 있는 게시글 표시

by 박채니 2022. 7. 2.

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

 

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


첨부파일 있는 게시글 표시

 

※ DB 구조 확인하기

https://chanychu.tistory.com/326?category=980487 

 

JSP) 게시판 페이지 구현 및 페이징 처리

안녕하세요, 코린이의 코딩 학습기 채니 입니다. 개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다. 게시판 페이지 구현 준비 header.jsp /board/boardList">게시판 클래스 구조 DB -- 게

chanychu.tistory.com

 

해당 게시글에 첨부파일이 존재한다면, 첨부파일이 있다는 표시를 해주려고 합니다.

 

기존 게시글과 동일한 구조 + 페이징이 적용되어있는 상태에서 첨부파일 표시만 추가한다고 하면,

아래와 같은 쿼리를 가지고 있어야합니다.

select 
    * 
from (
    select 
        row_number () over (order by no desc) rnum, 
        b.*,
       (select count(*) from attachment where board_no = b.no) attach_count
    from 
        board b
) b 
where
    rnum between 1 and 10;

하지만, Board객체에는 attach_count를 담은 공간이 존재하지 않기 때문에 Board를 상속한 BoardExt 클래스를 생성하여 제어해보려고 합니다.

 

Dto

BoardExt

public class BoardExt extends Board {
	private int attachCount;
	
	public BoardExt() {
		super();
		// TODO Auto-generated constructor stub
	}

	public BoardExt(int no, String title, String writer, String content, int readCount, Timestamp regDate) {
		super(no, title, writer, content, readCount, regDate);
	}

	public int getAttachCount() {
		return attachCount;
	}

	public void setAttachCount(int attachCount) {
		this.attachCount = attachCount;
	}

	@Override
	public String toString() {
		return "BoardExt [attachCount=" + attachCount + ", toString()=" + super.toString() + "]";
	}
}

 

Controller, Service는 동일 (위 URL 참고)

 

Dao

BoardDao

// findAll = select * from (select row_number () over (order by no desc) rnum, b.*, (select count(*) from attachment where board_no = b.no) attach_count from board b) b where rnum between ? and ?
public List<Board> findAll(Connection conn, Map<String, Object> param) {
    PreparedStatement pstmt = null;
    ResultSet rset = null;
    List<Board> boardList = new ArrayList<>();
    String sql = prop.getProperty("findAll");

    try {
        pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, (int)param.get("start"));
        pstmt.setInt(2, (int)param.get("end"));
        rset = pstmt.executeQuery();
        while(rset.next()) {
            BoardExt board = handleBoardResultSet(rset);
            board.setAttachCount(rset.getInt("attach_count"));
            boardList.add(board);
        }
    } catch (SQLException e) {
        throw new BoardException("게시글 전체 조회 오류!", e);
    } finally {
        close(rset);
        close(pstmt);
    }
    return boardList;
}

// getTotalContent = select count(*) from board 
public int getTotalContent(Connection conn) {
    PreparedStatement pstmt = null;
    ResultSet rset = null;
    int totalContent = 0;
    String sql = prop.getProperty("getTotalContent");

    try {
        pstmt = conn.prepareStatement(sql);
        rset = pstmt.executeQuery();
        if(rset.next()) {
            totalContent = rset.getInt(1);
        }
    } catch (SQLException e) {
        throw new BoardException("전체 게시글 수 조회 오류!", e);
    } finally {
        close(rset);
        close(pstmt);
    }
    return totalContent;
}

private BoardExt handleBoardResultSet(ResultSet rset) throws SQLException {
    int no = rset.getInt("no");
    String title = rset.getString("title");
    String writer = rset.getString("writer");
    String content = rset.getString("content");
    int readCount = rset.getInt("read_count");
    Timestamp regDate = rset.getTimestamp("reg_date");
    return new BoardExt(no, title, writer, content, readCount, regDate);
}

BoardExt 객체를 생성 및 반환하였고, 다형성이 적용되므로 List<Board>로 받아 사용할 수 있습니다.

while문 내에서 setAttachCount()하여 attachCount를 완성 시켜주었습니다.

 

boardList.jsp

<section id="board-container">
	<h2>게시판 </h2>
	<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><%= board.getTitle() %></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>

만일 attachCount가 존재한다면 (> 0), image파일이 보여지도록 하였고, List<Board>로 받았기 때문에 다운캐스팅을 해주었습니다.

 

첨부파일이 존재하는 게시글에 대해서는 위와 같이 파일 사진을 제공해주었습니다.