JSP + Servlet | MVC 패턴(모델 2) 게시판 구현 4/n(수정필요)

파과·2022년 7월 26일
0
post-custom-banner

20. BoardDAO에 메소드 추가

조회수를 세는 UpdateReadCount()와 게시글을 번호에 따라 가져오는 selectOneBoardByNum()을 추가한다.

package com.sw.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.sw.dto.BoardVO;

import util.DBManager;

public class BoardDAO {

	//싱글톤 패턴으로 만들기
	private BoardDAO() {
		
	}
	private static BoardDAO instance = new BoardDAO();
	
	public static BoardDAO getInstance() {
		return instance;
	}
	
	//게시판 테이블의 전체 데이터를 VO객체의 리스트로 받아오는 메소드. (한 행이 하나의 VO객체)
	public List<BoardVO> selectAllBoards(){
		String sql = "select * from board order by num desc";
		List<BoardVO> list = new ArrayList<BoardVO>();
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn = DBManager.getConnection();
			stmt = conn.createStatement();
			//조회 쿼리 실행
			rs = stmt.executeQuery(sql);
			while(rs.next()) {
				//한 행마다 VO객체를 하나씩 생성하고 set메소드로 해당 행의 컬럼값을 담음
				BoardVO bVo = new BoardVO();				
				bVo.setNum(rs.getInt("num"));
				bVo.setName(rs.getString("name"));
				bVo.setEmail(rs.getString("email"));
				bVo.setPass(rs.getString("pass"));
				bVo.setTitle(rs.getString("title"));
				bVo.setContent(rs.getString("content"));
				bVo.setReadcount(rs.getInt("readcount"));
				bVo.setWritedate(rs.getTimestamp("writedate"));
				list.add(bVo); //리스트의 마지막에 해당 VO객체를 추가함
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}finally {
			DBManager.close(conn, stmt, rs);
		}
		return list;
	}
	
	public void insertBoard(BoardVO bVo) {
		String sql = "insert into board("
				+ "num, name, email, pass, title, content)"
				+ "values(board_seq.nextval, ?, ?, ?, ?, ?)";
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		try {
			conn = DBManager.getConnection();
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, bVo.getName());
			pstmt.setString(2, bVo.getEmail());
			pstmt.setString(3, bVo.getPass());
			pstmt.setString(4, bVo.getTitle());
			pstmt.setString(5, bVo.getContent());
			
			pstmt.executeUpdate();
		}catch(SQLException e) {
			e.printStackTrace();
		}finally {
			DBManager.close(conn, pstmt);
		}
	}
	
	//조회수 구현
	public void updateReadCount(String num) {
		String sql = "update board set readcount = readcount+1 where num=?";
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			conn = DBManager.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, num);
			pstmt.executeUpdate();
		}catch(SQLException e) {
			e.printStackTrace();
		}finally {
			DBManager.close(conn, pstmt);
		}
	}
	
	public BoardVO selectOneBoardByNum(String num) {
		String sql = "select * from board where num = ?";
		BoardVO bVo = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			conn = DBManager.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, num);
			rs = pstmt.executeQuery();
			if(rs.next()) {
				bVo = new BoardVO();
				bVo.setNum(rs.getInt("num"));
				bVo.setName(rs.getString("name"));
				bVo.setPass(rs.getString("pass"));
				bVo.setEmail(rs.getString("email"));
				bVo.setTitle(rs.getString("title"));
				bVo.setContent(rs.getString("content"));
				bVo.setWritedate(rs.getTimestamp("writedate"));
				bVo.setReadcount(rs.getInt("readcount"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBManager.close(conn, pstmt, rs);
		}
		return bVo;
	}
}

21. com.sw.controller.action/BoardViewAction.java

게시글 상세 보기 페이지로 이동하게 하는 액션 클래스.
게시글 리스트에서 제목을 클릭하면 BoardServlet?command=board_view&num=${board.num}가 요청되어 게시글 상세보기 페이지로 이동해야 한다. 이 요청을 처리할 코드를 액션 클래스로 만들고 ActionFactory에 추가한다.

package com.sw.controller.action;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sw.dao.BoardDAO;
import com.sw.dto.BoardVO;

public class BoardViewAction implements Action{

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = "/board/boardView.jsp";
		
		String num = request.getParameter("num");
		
		BoardDAO bDao = BoardDAO.getInstance();
		
		bDao.updateReadCount(num);
		
		BoardVO bVo = bDao.selectOneBoardByNum(num);
		
		request.setAttribute("board", bVo);
		
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}
	
}

22. WebContent/board/boardView.jsp

게시글 상세 보기를 위한 jsp페이지

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="css/shopping.css">
<script type="text/javascript" src="script/board.js"></script>
</head>
<body>
	<div id="wrap" align="center">
		<h1>게시글 상세보기</h1>
		<table>
			<tr>
				<th>작성자</th>
				<td>${board.name}</td>
				<th>이메일</th>
				<td>${board.email}</td>
			</tr>
			<tr>
				<th>작성일</th>
				<td><fmt:formatDate value="${board.writedate}" /></td>
				<th>조회수</th>
				<td>${board.readcount }</td>
			</tr>
			<tr>
				<th>제목</th>
				<td colspan="3">${board.title }</td>
			</tr>
			<tr>
				<th>내용</th>
				<td colspan="3"><pre>${board.content }</pre></td>
			</tr>
		</table>
		<!--4개의 버튼에 있는 코드는 무조건 암기. -->
		<br> <br> <input type="button" value="게시글 수정"
			onclick="open_win('BoardServlet?command=board_check_pass_form&num=${board.num}', 'update')">
		<input type="button" value="게시글 삭제"
			onclick="open_win('BoardServlet?command=board_check_pass_form&num=${board.num}', 'delete')">
		<input type="button" value="게시글 리스트"
			onclick="location.href='BoardServlet?command=board_list'"> 
		<input type="button" value="게시글 등록"
			onclick="location.href='BoardServlet?command=board_write_form'">
	</div>
</body>
</html>

23. ActionFactory 수정하기

else if(command.equals("board_view")) {
			action = new BoardViewAction();
		}

게시글 수정

게시글 수정을 클릭하면 게시글을 등록할 때 입력했던 게시글 비밀번호를 묻는 창이 뜬다.

  • 팝업창은 자바스크립트의 window.open()함수를 사용한다.
  • 팝업창의 첫번째 매개변수에 비밀번호 입력을 위한 폼을 띄우는 요청을 한다.

이 요청을 처리할 코드를 액션 클래스로 만들고 ActionFactory에 추가한다. 액션 클래스에서는 비밀번호 입력 화면으로 이동하도록 한다.

24. com.sw.controller.action/BoardCheckPassFormAction.java

비밀번호 입력 화면으로 이동하게 하는 액션 클래스

package com.sw.controller.action;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BoardCheckPassFormAction implements Action {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = "/board/boardCheckPass.jsp";
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}
	
}

25. WebContent/board/boardCheckPass.jsp

비밀번호 입력 화면을 위한 jsp 페이지

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="css/shopping.css">
<script type="text/javascript" src="script/board.js"></script>
</head>
<body>
  <div align="center">
    <h1>비밀번호 확인</h1>
    <form action="BoardServlet" name="frm" method="get">
      <input type="hidden" name="command" value="board_check_pass">
      <input type="hidden" name="num" value="${param.num}">
      <table style="width: 80%">
        <tr>
          <th>비밀번호</th>
          <td><input type="password" name="pass" size="20"></td>
        </tr>
      </table>
      <br><input type="submit" value="확인" onclick="return passCheck()"><br><br>
      ${message}
    </form>
  </div>
</body>
</html>

26. ActionFactory 수정하기

else if(command.equals("board_check_pass_form")) {
			action = new BoardCheckPassFormAction();
		}

27. com.sw.controller.action/BoardCheckPassAction.java

게시글의 비밀번호를 확인하기 위한 액션 클래스

package com.sw.controller.action;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BoardCheckPassAction implements Action{

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = "/board/boardCheckPass.jsp";
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}
	
}

28. WebContent/board/checkSuccess.jsp

게시글의 비밀번호가 일치할 경우 처리를 위한 jsp페이지

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<script type="text/javascript">
		if(window.name == "update"){
			window.opener.parent.location.href = "BoardServlet?command=board_update_form&num=${param.num}";
		}else if(window.name == 'delete'){
			alert('삭제되었습니다.');
			window.opener.parent.location.href = "BoardServlet?command=board_delete&num=${param.num}";
		}
		window.close();
	</script>
</body>
</html>

29. ActionFactory 수정하기

else if(command.equals("board_check_pass")) {
			action = new BoardCheckPassAction();
		}

30. com.sw.controller.action/BoardUpdateFormAction.java

게시글 수정을 위해 비밀번호를 입력할 경우 BoardServlet?command=board_update_form&num=${param.num}가 요청된다. 이 요청을 처리할 코드를 액션 클래스를 만들어 ActionFactory에 추가한다. 액션 클래스에서는 게시글 수정을 위한 화면으로 이동하도록 한다.

package com.sw.controller.action;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sw.dao.BoardDAO;
import com.sw.dto.BoardVO;

public class BoardUpdateFormAction implements Action{

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = "/board/boardUpdate.jsp";
		String num = request.getParameter("num");
		BoardDAO bDao = BoardDAO.getInstance();
		bDao.updateReadCount(num);
		BoardVO bVo = bDao.selectOneBoardByNum(num);
		request.setAttribute("board", bVo);
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response);
		
	}
	
}
post-custom-banner

2개의 댓글

comment-user-thumbnail
2022년 8월 19일

왠지 BoardCheckPassAction.java 의 내용이 빠진거 같습니다

1개의 답글