Servlet/JSP 답변형 게시판 만들기 - 등록

코코·2020년 8월 18일
0

게시물 등록

DAO

테스트

   @Test
    public void insertTest() throws ClassNotFoundException{
    	Class.forName(DRIVER);
    	
    	String sql = "INSERT INTO t_board(title, content, imgName, id, p_bno)"
    			+" VALUES(?,?,?,?,?)";
    	log.info(sql);
    	
    	try(
    		Connection conn = DriverManager.getConnection(URL,USER,PW);
    		PreparedStatement pstmt = conn.prepareStatement(sql);
    		) {
    		
    		log.info(conn.toString());
    		log.info(pstmt.toString());
    		
    		for (int i=1; i<=3; i++) {
    			pstmt.setString(1, "하이룽" + i);
    			pstmt.setString(2, "hello world " + i);
    			pstmt.setString(3, null);
    			pstmt.setString(4, "wooa");
    			
    			//0 : 자신이 원글.
    			//그 외 숫자 : 부모 글의 게시물 번호(bno)
    			//pstmt.setInt(5, 2); //2번 글의 답변글
    			pstmt.setInt(5, 0);
    			
    			//성공하면 1을 반환한다.
        		int result = pstmt.executeUpdate();
        		
        		//result가 1이 아니라면 테스트 실패
        		assertTrue(result == 1);
    		}
    	} catch(Exception e) {
    		e.printStackTrace();
    	}
    }

프로젝트

DAO

public class BoardDAO {
	private final static Logger log = Logger.getGlobal();
	DataSource ds;
    ...
    ...
	public int insert(BoardVO vo) {
    	String sql = "INSERT INTO t_board(title, content, imgName, id, p_bno)"
    			+" VALUES(?,?,?,?,?)";
		
    	log.info(sql);
    	
    	try(
			Connection conn = ds.getConnection();
			PreparedStatement pstmt = conn.prepareStatement(sql);
			){
			pstmt.setString(1, vo.getTitle());
			pstmt.setString(2, vo.getContent());
			pstmt.setString(3, vo.getImgName());
			pstmt.setString(4, vo.getId());
			pstmt.setInt(5, vo.getP_bno());
			
			return pstmt.executeUpdate();
			
		}catch(Exception e) {e.printStackTrace();}
		return -1;
	}
...
...
} // end - class

Service

public class BoardServiceImpl implements BoardService {

	private BoardDAO dao;
	
	public BoardServiceImpl() {
		//초기화
		dao = new BoardDAO();
	}
    
    ....
    	@Override
	public int register(BoardVO vo) {
		return dao.insert(vo);
	}
} // end - service

Controller

@WebServlet("/board/*")
public class BoardController extends HttpServlet {
	private final static Logger log = Logger.getGlobal();

	...
    
    	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);
        
        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");
			int p_bno = Integer.parseInt(request.getParameter("p_bno"));
			
			//받아온 데이터로 VO객체를 생성한다.
			BoardVO vo = new BoardVO();
			
			vo.setTitle(title);
			vo.setContent(content);
			vo.setImgName(imgName);
			vo.setId(id);
			vo.setP_bno(p_bno);
			
			log.info("vo : " + vo);
			
			//데이터베이스에 저장하는 메서드에 vo를 전달한다.
			//결과가 1이라면 성공, 그 외는 실패..
			nextPage = boardService.register(vo) == 1
							? "/board/list" : "error";
		}
        
        RequestDispatcher dispatcher = request.getRequestDispatcher(nextPage);
		dispatcher.forward(request, response);
	}
}

view

...
<form name='action' method='post' action='/board/register'>
	<table>
		<tr>
			<td align="right"> 제목 </td>
			<td clspan='2'><input type='text' name='title' size='67' maxlength="50"></td>
		</tr>
		<tr>
			<td align="right" valign="top"><br> 내용 </td>
			<td colspan="2"><textarea rows="10" cols="65" name='content'></textarea></td>
		</tr>
		<tr>
			<td align="right"> 작성자 </td>
			<td clspan='2'><input type='text' name='id' maxlength="50"></td>
		</tr>
		<tr>
			<td align="right"> </td>
			<td colspan="2">
				<input type='submit' value='글쓰기'>
				<input type='button' id='list' value='목록'>
			</td>
		</tr>
	</table>
</form>
<script type="text/javascript">
	window.onload = () => {
		const list = document.getElementById('list')
		
		list.addEventListener("click", () => {
			location.replace('/board/list')
		})
	}
</script>
...

제대로 등록이 되는지 확인한다.

0개의 댓글