게시판(2) 조회수 증가, 글쓰기, 댓글

최현석·2022년 10월 30일
0

JSP

목록 보기
13/13

🧩BoardFrontController

@WebServlet("*.bo")
public class BoardFrontController extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doProcess(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doProcess(req, resp);
	}

	protected void doProcess(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String requestURI = req.getRequestURI();
		ActionForward forward = null;

//		if (requestURI.equals("/board/BoardList.bo")) {
//			forward = new ActionForward(false, "/board/boardlist.jsp");
//		} 

		switch (requestURI) {
			case "/board/BoardList.bo":
	//			forward = new ActionForward(false,"/board/boardlist.jsp");
	
				// 목록 가져오기
				forward = new BoardListAction().execute(req, resp);
				break;
				
				// 클릭시 화면이동
			case "/board/BoardView.bo":
//				forward = new ActionForward(false,"/board/boardview.jsp");
				forward = new BoardViewAction().execute(req, resp);
				break;
				
			case "/board/BoardWrite.bo":
				forward = new ActionForward(false,"/board/boardwrite.jsp");
				break;
				
				// 글 등록
			case "/board/BoardWriteOk.bo":
				forward = new BoardWriteOkAction().execute(req, resp);
				break;
                
				// 댓글
			case "/board/AddReply.bo":
				forward = new AddReplyAction().execute(req, resp);
				break;

		}
		
		// 페이지 이동 일괄처리
		if (forward != null) {
			if (forward.isRedirect()) {
				// redirect
				resp.sendRedirect(forward.getPath());
			} else {
				// forward
				RequestDispatcher disp = req.getRequestDispatcher(forward.getPath());
				disp.forward(req, resp);
			}
		}

	}

}

🧩BoardViewAction

-> BoardViewAction -> 프론트 컨트롤러 -> 보드뷰로 요청이온다

  • href="pageContext.request.contextPath/board/BoardView.bo?boardnum={pageContext.request.contextPath }/board/BoardView.bo?boardnum={board.boardnum }"
  • 보드리스트에서 제목 클릭했을 때 넘버값을 파라미터 값으로 넘겨줌
  • 이곳에서 파라미터 값을 꺼내온다
  • DAO를 2번 다녀온다.(조회수 증가)
public class BoardViewAction implements Action{

	@Override
	public ActionForward execute(HttpServletRequest req, HttpServletResponse resp) {
		ActionForward forward = new ActionForward();
		BoardDAO bdao = new BoardDAO();
		
		int boardnum = Integer.parseInt(req.getParameter("boardnum"));
		
		//조회수를 update
		bdao.updateReadCount(boardnum);
		
		
		req.setAttribute("board", bdao.getDetail(boardnum));
		

		forward.setRedirect(false);
		forward.setPath("/board/boardview.jsp" );
		
		
		return forward;
	}
	
}

🧩BoardDAO

	// 결과값은 BoardDTO에 담아서 가져온다
	public BoardDTO getDetail(int boardnum) {
		// object로 형변환이 되므로, BoardDTO로 바꿔준다.
		// boardnum 파라미터로 넘겨서 가져온다.
		return (BoardDTO) sqlsession.selectOne("Board.getDetail", boardnum);
	}
    
    // 조회수 증가
	public void updateReadCount(int boardnum) {
		sqlsession.update("Board.updateReadCount", boardnum);

	}

	// 글 등록
	public boolean insertBoard(BoardDTO board) {
		boolean result = false;

		if (sqlsession.insert("Board.insertBoard", board) == 1) {
			result = true;
		}

		return result;
	}

	// 획득을 위한 db다녀오기
	public int getSeq() {
		return sqlsession.selectOne("Board.getSeq");
	}

	public boolean addReply(ReplyDTO reply) {
		boolean result = false;
		// 다오 분리 o or x
		if(sqlsession.insert("Board.addReply",reply)==1) {
			result = true;
		}
		
		return result;
			
	}

🧩Board.xml

	<select id="getDetail" parameterType="_int" resultType="boarddto">
		SELECT * FROM TBL_BOARD tb where boardnum = #{boardnum}
	</select>
	
 <!-- 조회수 증가 -->
	<update id="updateReadCount" parameterType="_int">
		UPDATE TBL_BOARD SET BOARDREADCOUNT = BOARDREADCOUNT + 1 WHERE BOARDNUM = #{boardnum}
	</update>
		
		<!-- 글 등록 -->
	<insert id="insertBoard" parameterType="boarddto">
		INSERT INTO TBL_BOARD VALUES (board_seq.nextval, #{boardtitle}, #{boardcontents}, #{username}, sysdate, 0)
	</insert>
	

	<select id="getSeq" resultType="_int">
		select board_seq.currval FROM dual
	</select>
	
	<insert id="addReply" parameterType="replydto">
		INSERT INTO TBL_REPLY VALUES(reply_seq.nextval,#{replycontents},#{username}, #{password}, #{boardnum})
	</insert>

🧩boardview.jsp 댓글

<body>
	<!-- td에 넣어준다 -->	
	<c:set var="board" value="${requestScope.board }"/>


	<div>
		<table style="width: 900px; border: 0px;">
			<tr align="center" valign="middle">
				<td><h3>MVC 게시판</h3></td>
			</tr>
		</table>
	
		<table border="1" style="border-collapse: collapse;">	
		
			<tr height="30px;">
				<th align="center" width="150px;">제목</th>
				<td>
					${board.boardtitle }
					<span style="font-weight: bold; color:#6a1b9a;float: right;">
						조회수 : ${board.boardreadcount }
						
					</span>
				</td>
			</tr>
			
			<tr height="30px;">
				<th align="center" width="150px;">글쓴이</th>
				<td>${board.username }</td>
			</tr>
		
			<tr height="300px;">
				<th align="center" width="150px;">내용</th>
				<td  valign="top" style="padding: 10px;">${board.boardcontents }</td>
			</tr>
			
		</table>
		
		<table style="border: 0px;">
			<tr align="right" valign="middle">
				<td>
                			<!--프론트 컨트롤러를 갔다가 화면 응답 페이지까지 던져준다. -->

					<a href="${pageContext.request.contextPath }/board/BoardList.bo">[목록]</a>
				</td>
			</tr>
		</table>
		
		<!-- 댓글 -->
		<hr>
		<form action="${pageContext.request.contextPath }/board/AddReply.bo" name="replyForm" method="post">
			<!-- 히든으로 가려준다. -->
			<input type="text" name="boardnum" value="${board.boardnum }">
			<table>
				<tr>
					<td align="center" width="200px;">
						댓글<br><hr>
						이름&nbsp;&nbsp;&nbsp;&nbsp;<input name="username" maxlength="10" size="10"><br>
						비밀번호<input type="password" name="password" size="10">
					</td>
					
					<td style="padding-left :10px;">
						<textarea style="width: 680px;height:85px;resize: none;" name="replycontents"></textarea>
						<a href="javascript:document.replyForm.submit()">[등록]</a>
					</td>
				</tr>
			</table>
		
		</form>			
		
	</div>

</body>

🧩boardwrite.jsp 글쓰기

<body>
	<div>
		<form action="${pageContext.request.contextPath }/board/BoardWriteOk.bo" method="post" name="boardForm">
			<table style="width: 900px;border: 0px;">
				<tr align="center" valign="middle">
					<td><h3>MVC 게시판</h3></td>
				</tr>
			</table>
			
			<table border="1" style="border-collapse: collapse;">
				<tr height="30px;">
					<th align="center" width="150px;">제목</th>
					<td>
						<input name="boardtitle" size="50" maxlength="100" placeholder="제목을 입력하세요.">
					</td>
				</tr>
				<tr height="30px;">
					<th align="center" width="150px;">글쓴이</th>
					<td>
						<input name="username" size="50" maxlength="20" placeholder="이름을 입력하세요.">
					</td>
				</tr>
				<tr height="30px;">
					<th align="center" width="150px;">내용</th>
					<td><textarea name="boardcontents" style="width: 700px;height: 250px;"></textarea> </td>
				</tr>
			</table>
			
			<table style="border: 0px;">
				<tr align="right" valign="middle">
					<td>
						<a href="javascript:document.boardForm.submit();">[등록]</a>&nbsp;&nbsp;&nbsp;&nbsp;
						<a href="${pageContext.request.contextPath }/board/BoardList.bo">[목록]</a>
					</td>
				</tr>
			</table>
		</form>	
	</div>
</body>	

🧩BoardWriteOkAction

public class BoardWriteOkAction implements Action{

	@Override
	public ActionForward execute(HttpServletRequest req, HttpServletResponse resp) {
		ActionForward forward = new ActionForward();
		BoardDAO bdao = new BoardDAO();
		
		// 화면에서 넘겨받을 파라미터 
		String boardtitle = req.getParameter("boardtitle");
		String boardcontents = req.getParameter("boardcontents");
		String username = req.getParameter("username");
		
		//조회수를 update
		BoardDTO board = new BoardDTO();
		board.setBoardtitle(boardtitle);
		board.setBoardcontents(boardcontents);
		board.setUsername(username);
		
		
		// 성공이든 실패든 데이터를 지워준다.
		// 실패시 데이터를 남아있게 하고싶으면 if문 각각에 setRedirect방식을 다르게 설정
		forward.setRedirect(true);
		
		// xml에서 true,false로 결과값을 받아온다
		if(bdao.insertBoard(board)) {
			// 성공시
            // 목록에 글이 하나 추가되고 작성한 화면을 바로 보여준다
            
            // 파라미터 값(boardnum=)이 필요하다.
			// seq로 증가하고있는 값을 알아야한다 그래야 파라미터값으로 넘겨줄수있다. 
			int boardnum=bdao.getSeq(); //seq를 획득을 위한 db를 다녀온다.
			forward.setPath(req.getContextPath() + "/board/BoardView.bo?boardnum=" + boardnum);
		}else {
			// 실패시
            // 글 등록 실패시 다시 BoardWrtie 작성화면을 보여준다.
			// JSP페이지를 바로 호출하면 그 안에서 DB처리가 안된 상태의 페이지를 불러올수 있다.
			// 프론트 컨트롤러를 거쳐서 요청을 해야한다.
			forward.setPath(req.getContextPath() + "/board/BoardWrite.bo" );
		}
		
		
		return forward;
	}
		
}

🧩DB 댓글 테이블

-------------------댓글 테이블 생성
CREATE TABLE tbl_reply(
	replynum		number(10)	PRIMARY KEY,
	replycontents	varchar2(600),
	username		varchar2(300),
	password		varchar2(300),
	boardnum		number(10),
	CONSTRAINTS rep_bd_fk FOREIGN KEY(boardnum) REFERENCES tbl_board(boardnum)
);

SELECT * FROM TBL_REPLY  ;

CREATE SEQUENCE reply_seq
START WITH 1
INCREMENT BY 1;

INSERT INTO TBL_REPLY VALUES(reply_seq.nextval,'댓글2','user1', '1234', 142);

🧩AddReplyAction

public class AddReplyAction implements Action{

	@Override
	public ActionForward execute(HttpServletRequest req, HttpServletResponse resp) {
		ActionForward forward = new ActionForward();
		
		BoardDAO bdao = new BoardDAO();
		ReplyDTO reply = new ReplyDTO();
		
		int boardnum = Integer.parseInt(req.getParameter("boardnum"));
		
		reply.setBoardnum(boardnum);
		reply.setUsername(req.getParameter("username"));
		reply.setPassword(req.getParameter("password"));
		reply.setReplycontents(req.getParameter("replycontents"));
		
		if(bdao.addReply(reply)) {
        	// 앞에 넘겨받아온 비밀번호 같은 것 들을 날려줘한다
			forward.setRedirect(true);
            // 글 상세보기 화면으로 이동 -> 상세보기 페이지는 boardnum 파라미터도 같이 넘겨줘야한다.
			forward.setPath(req.getContextPath() + "/board/BoardView.bo?boardnum="+boardnum);
		}
		
		return forward;
	}
	
}

🧩ReplyDTO

public class ReplyDTO {
	private int replynum;
	private String replycontents;
	private String username;
	private String password;
	private int boardnum;
	
	public int getReplynum() {
		return replynum;
	}
	public void setReplynum(int replynum) {
		this.replynum = replynum;
	}
	public String getReplycontents() {
		return replycontents;
	}
	public void setReplycontents(String replycontents) {
		this.replycontents = replycontents;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getBoardnum() {
		return boardnum;
	}
	public void setBoardnum(int boardnum) {
		this.boardnum = boardnum;
	}
}

🧩config.xml

	<typeAliases>
		<typeAlias type="com.koreait.board.dao.BoardDTO" alias="boarddto"/>	
        // 추가
		<typeAlias type="com.koreait.board.dao.ReplyDTO" alias="replydto"/>	
	</typeAliases>

🧩결과


0개의 댓글