Servlet/JSP 답변형 게시판 만들기 - 조회

코코·2020년 8월 17일
0

com.test.BoardDAO

   @Test
    public void getPostTest() throws ClassNotFoundException {
    	Class.forName(DRIVER);
    	String sql = "SELECT * FROM t_board"
    			+" WHERE bno > 0 AND bno = ?";
    	log.info(sql);
    	
    	try(
    		Connection conn = DriverManager.getConnection(URL,USER,PW);
    		PreparedStatement pstmt = conn.prepareStatement(sql);
    		) {
			pstmt.setInt(1, 7);
			ResultSet rs = pstmt.executeQuery();
    		
			assertNotNull(rs);
			
			rs.next();

			BoardVO vo = new BoardVO();
			
			vo.setBno(rs.getInt("bno"));
			vo.setP_bno(rs.getInt("p_bno"));
			vo.setTitle(rs.getString("title"));
			vo.setContent(rs.getString("content"));
			vo.setImgName(rs.getString("imgName"));
			vo.setId(rs.getString("id"));
			vo.setRegdate(rs.getDate("regdate"));

			log.info("vo : " + vo);

    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    }

com.coco.dao.BoardDAO

	public BoardVO getPost(int no) {
		log.info("no : " + no);
    	String sql = "SELECT * FROM t_board"
    			+" WHERE bno > 0 AND bno = ?";
    	log.info(sql);
       	try(
        	Connection conn = ds.getConnection();
        	PreparedStatement pstmt = conn.prepareStatement(sql);
        	) {
    		pstmt.setInt(1, no);
    		ResultSet rs = pstmt.executeQuery();
    			
    		rs.next();

    		BoardVO vo = new BoardVO();
    			
    		vo.setBno(rs.getInt("bno"));
    		vo.setP_bno(rs.getInt("p_bno"));
    		vo.setTitle(rs.getString("title"));
    		vo.setContent(rs.getString("content"));
    		vo.setImgName(rs.getString("imgName"));
    		vo.setId(rs.getString("id"));
    		vo.setRegdate(rs.getDate("regdate"));

    		log.info("vo : " + vo);
    		
    		return vo;

        } catch (Exception e) {
        	e.printStackTrace();
        }
		
		return null;
	}

com.coco.service.BoardService

package com.coco.service;

import java.util.List;

import com.coco.vo.BoardVO;

public interface BoardService {
	List<BoardVO> getList();
	int register(BoardVO vo);
    
    //추가
	BoardVO getPost(int no);
	
}

package com.coco.service;

import java.util.List;

import com.coco.dao.BoardDAO;
import com.coco.vo.BoardVO;

public class BoardServiceImpl implements BoardService {

	private BoardDAO dao;
	
	public BoardServiceImpl() {
		//초기화
		dao = new BoardDAO();
	}
	
	@Override
	public List<BoardVO> getList() {
		return dao.getList();
	}

	@Override
	public int register(BoardVO vo) {
		return dao.insert(vo);
	}

//추가
	@Override
	public BoardVO getPost(int no) {
		return dao.getPost(no);
	}
}

com.coco.controller.BoardController

	private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		BoardService boardService = new BoardServiceImpl();
		String nextPage = "";
		String action = request.getPathInfo();	//어떤 url을 요청했는가?
		List<BoardVO> list;
		log.info("action : " + action);
		
		/* 클라이언트가 요청한 URL이 '/board' 또는 '/board/list'일 경우
		 * service에서 게시글 목록을 불러오는 메서드를 바인딩 해서 화면으로 보낸다.
		 */
		if(action == null || action.equals("/list")) {
			request.setAttribute("boardList", boardService.getList());
			nextPage="/WEB-INF/board/list.jsp";
		} else if(action.equals("/write")) {
			nextPage = "/WEB-INF/board/write.jsp";
			
		}  else if (action.equals("/register")) {
			//등록한 게시물 데이터를 받아온다.
			String title = request.getParameter("title");
			String content = request.getParameter("content");
			String imgName = request.getParameter("imgName");
			String id = request.getParameter("id");
			
			//받아온 데이터로 VO객체를 생성한다.
			BoardVO vo = new BoardVO(title, content, imgName, id);
			
			log.info("vo : " + vo);
			
			//데이터베이스에 저장하는 메서드에 vo를 전달한다.
			//결과가 1이라면 성공, 그 외는 실패..
			nextPage = boardService.register(vo) == 1
							? "/board/list" : "error";
		} else if(action.equals("/post")) {
			//조회한 게시물 번호
			int no = Integer.parseInt(request.getParameter("no"));
			
			//게시물을 조회하는 메서드에 게시물 번호를 인자로 넘기고, 결과를 받는다.
			request.setAttribute("post", boardService.getPost(no));

			nextPage="/WEB-INF/board/post.jsp";
		}
		
		RequestDispatcher dispatcher = request.getRequestDispatcher(nextPage);
		dispatcher.forward(request, response);
	}

post.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>[${post.bno}번 게시물] ${post.title }</title>
</head>
<body>
<h1>게시물 조회</h1>
<form action="/board/mod">
	<table>
		<tr>
			<td width="20%" align="center"> 제목 </td>
			<td> <input type='text' name='title' value='${post.title }' disabled></td>
		</tr>
		<tr>
			<td width="20%" align="center"> 내용 </td>
			<td>
				<textarea rows="20" cols="60" name='content' disabled>${post.content }</textarea>
			</td>
		</tr>
		<tr>
			<td width="20%" align="center"> 작성자 </td> 
			<td><input type='text' name='id' value='${post.id }' disabled></td> 
		</tr>
		<tr>
			<td align="right"><input type='submit' value='수정'>
			<input type='button' id='remove' value='삭제'> 
			<input type='button' id='list' value='목록'>
			<input type='button' id='rePost' value='답글'></td> 
		</tr>
	</table>
	
	<input type='hidden' id='bno' name='bno' value='${bno }'>
</form>
<script>
	window.onload = () => {
		const remove = document.getElementById('remove')
		const list = document.getElementById('list')
		const rePost = document.getElementById('rePost')

		console.log(remove)
		console.log(list)
		console.log(rePost)
		
		list.addEventListener("click", () => {
			location.replace('/board/list')
		})
  	}

</script>
</body>
</html>

0개의 댓글