오늘이라도

[Web] 32. 회원 관리 & 게시판 만들기 ⑦ : 답글 쓰기 본문

취업성공패키지 SW 개발자 교육/Web

[Web] 32. 회원 관리 & 게시판 만들기 ⑦ : 답글 쓰기

upcake_ 2020. 6. 24. 18:28
반응형

https://github.com/upcake/Class_Examples

교육 중에 작성한 예제들은 깃허브에 올려두고 있습니다. 

gif 파일은 클릭해서 보는 것이 정확합니다.


 - 회원 관리 & 게시판 만들기 ⑦ :  답글 쓰기 -

▲답글 쓰기 작동 화면

 

<%@page import="com.board.study.BoardDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String id = (String) (session.getAttribute("id"));
BoardDTO dto = (BoardDTO) request.getAttribute("dto");

String board_content = dto.getBoard_content();
String replaceContent = board_content.replaceAll("\r\n", "<br/>");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>board view jsp</title>
<script type="text/javascript">
function fnReply(num) {
	if(confirm("답글을 작성하시겠습니까?")) {
		location.href = "boardReplyView.bo?board_num=" + num;
	}
}

function fnUpdate(num) {
	if(confirm("수정하시겠습니까?")) {
		location.href = "boardModifyView.bo?board_num=" + num;
	}
	return false;
}

function fnDelete(num) {
	if(confirm("정말 삭제하시겠습니까?")) {
		location.href = "boardDeleteAction.bo?board_num=" + num;
	}
	return false;
}

</script>
</head>
<body>
<div align="center">
	<h3>[상세 글 보기]</h3>
	<table border="1">
		<tr>
			<th>제목</th>
			<td><%=dto.getBoard_subject() %></td>		
			<th>조회수</th>
			<td align="center"><%=dto.getBoard_readcount() %></td>
		</tr>
		<tr>
			<th>내용</th>
			<td colspan="3" width="500"><%=replaceContent %></td>
		</tr>
		<tr>
			<th>첨부 파일</th>
			<td colspan="3" >
				<%if(dto.getBoard_file() == null) { %>
					첨부된 파일이 없습니다.
				<%} else { %>
					<a href="boardupload/<%=dto.getBoard_file()%>"><%=dto.getBoard_file() %></a>
				<%} %>
			</td>
		</tr>
		<tr align="center">
			<td colspan="4">
				<input type="button" value="답글쓰기" onclick="fnReply('<%=dto.getBoard_num() %>')"/>
				<input type="button" value="수정하기" onclick="fnUpdate('<%=dto.getBoard_num() %>')" />
				<input type="button" value="삭제하기" onclick="fnDelete('<%=dto.getBoard_num() %>')" />
				<input type="button" value="목록보기" onclick="location.href='boardList.bo'"/>
			</td>
		</tr>
	</table>
</div>
</body>
</html>

▲board_view.jsp

 

package com.board.action;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.commons.action.Action;
import com.commons.action.ActionForward;

@WebServlet("/BoardFrontController.bo")
public class BoardFrontController extends HttpServlet {
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uri = request.getRequestURI();
		String context = request.getContextPath();
		String command = uri.substring(context.length());
		//System.out.println(command);	//콘솔 창에 /memberLogin.me 등이 출력된다.
		
		Action action = null;
		ActionForward forward = null;
		
		if(command.equals("/boardList.bo")) {
			action = new BoardListAction();
			forward = action.execute(request, response);
		} else if(command.equals("/boardWrite.bo")) {
			forward = new ActionForward();
			forward.setPath("board/board_write.jsp");
			forward.setRedirect(false);
			//가져갈게 있으면 true(forward) 없으면 false(sendRedirect)
			//URL 바뀌면 true(boardWrite.bo로 바뀌어서 안됨) 안바뀌면 false
		} else if(command.equals("/boardAddAction.bo")) {
			action = new BoardAddAction();
			forward = action.execute(request, response);
		} else if(command.equals("/boardDetailAction.bo")) {
			action = new BoardDetailAction();
			forward = action.execute(request, response);
		} else if(command.equals("/boardDeleteAction.bo")) {
			action = new BoardDeleteAction();
			forward = action.execute(request, response);
		} else if(command.equals("/boardModifyView.bo")) {
			action = new BoardModifyView();
			forward = action.execute(request, response);
		} else if(command.equals("/boardModifyAction.bo")) {
			action = new BoardModifyAction();
			forward = action.execute(request, response);
		} else if(command.equals("/boardReplyView.bo")) {
			action = new BoardReplyView();
			forward = action.execute(request, response);
		} else if(command.equals("/boardReplyAction.bo")) {
			action = new BoardReplyAction();
			forward = action.execute(request, response);
		}
		
		if(forward != null) {
			if(forward.isRedirect()) {	//true : sendRedirect() 전환
				response.sendRedirect(forward.getPath());
			} else {					//false : forward() 전환
				RequestDispatcher rd = request.getRequestDispatcher(forward.getPath());
				rd.forward(request, response);
			}
		}
	}
}

▲BoardFrontController.java

 

package com.board.action;

import java.io.IOException;

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

import com.board.study.BoardDAO;
import com.board.study.BoardDTO;
import com.commons.action.Action;
import com.commons.action.ActionForward;

public class BoardReplyView implements Action {
	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int board_num = Integer.parseInt(request.getParameter("board_num"));
		BoardDAO dao = new BoardDAO();
		BoardDTO dto = dao.getDetail(board_num);
		request.setAttribute("dto", dto);
		
		ActionForward forward = new ActionForward();
		forward.setPath("board/board_reply.jsp");
		forward.setRedirect(false);
		return forward;
	}
}

▲BoardReplyView.java

 

<%@page import="com.board.study.BoardDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
BoardDTO dto = (BoardDTO) request.getAttribute("dto");
String id = (String) session.getAttribute("id");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>board reply JSP</title>
</head>
<body>
<div align="center">
	<h3>[답글 쓰기]</h3>
	<form action="boardReplyAction.bo" method="post">
	<input type="hidden" name="board_id" value="<%=id %>" />
	<input type="hidden" name="board_num" value="<%=dto.getBoard_num() %>" />
	<input type="hidden" name="board_re_ref" value="<%=dto.getBoard_re_ref() %>" />
	<input type="hidden" name="board_re_lev" value="<%=dto.getBoard_re_lev() %>" />
	<input type="hidden" name="board_re_seq" value="<%=dto.getBoard_re_seq() %>" />
		<table border="1">
			<tr>
				<th>작성자</th>
				<td><%=id %></td>
			</tr>
			<tr>
				<th>제목</th>
				<td><input type="text" name="board_subject" required="required" /></td>
			</tr>
			<tr>
				<th>내용</th>
				<td>
					<textarea rows="15" cols="50" name="board_content" required="required"></textarea>
				</td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					<input type="submit" value="답글등록" />
					<input type="button" value="취소하기" onclick="history.go(-1)"/>
					<input type="button" value="목록보기" onclick="location.href='boardList.bo'"/>
				</td>
			</tr>
		</table>
	</form>
</div>
</body>
</html>

▲board_reply.jsp

 

package com.board.action;

import java.io.IOException;
import java.io.PrintWriter;

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

import com.board.study.BoardDAO;
import com.board.study.BoardDTO;
import com.commons.action.Action;
import com.commons.action.ActionForward;

public class BoardReplyAction implements Action {
	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		BoardDTO dto = new BoardDTO();
		int board_num = Integer.parseInt(request.getParameter("board_num"));
		dto.setBoard_num(board_num);
		dto.setBoard_id(request.getParameter("board_id"));
		dto.setBoard_subject(request.getParameter("board_subject"));
		dto.setBoard_content(request.getParameter("board_content"));
		dto.setBoard_re_ref(Integer.parseInt(request.getParameter("board_re_ref")));
		dto.setBoard_re_lev(Integer.parseInt(request.getParameter("board_re_lev")));
		dto.setBoard_re_seq(Integer.parseInt(request.getParameter("board_re_seq")));
		
		BoardDAO dao = new BoardDAO();
		int succ = dao.boardReply(dto);
		
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		if (succ > 0) {
			out.println("<script>alert('답글 등록 성공');");
			out.println("location.href='boardDetailAction.bo?board_num=" + board_num + "';</script>");
		} else {
			out.println("<script>alert('답글 등록 실패');");
			out.println("history.go(-1);</script>");
		}
		return null;
	}
}

▲BoardReplyAction.java

 

package com.board.study;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class BoardDAO {
	private Connection conn;
	private PreparedStatement ps;
	private ResultSet rs;
	
	public Connection getConn() {
		String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
		String user = "hanul";
		String password = "0000";
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("getConn() Exception!!!");
		}
		return conn;
	} //getConn()

	//게시글 등록
	public int boardInsert(BoardDTO dto) {
		conn = getConn();
		String sql = "";
		int b_num = 0;
		int succ = 0;
		try {
			//글 번호를 검색한 후 등록할 글 번호(b_num)를 결정
			sql = "SELECT MAX(board_num) FROM memberBoard";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			
			if(rs.next()) { //글이 있으면 (글 갯수 + 1)번
				b_num = rs.getInt(1);
				b_num += 1;
			} else { // 글이 없으면 1번
				b_num = 1;
			}
			
			//글 등록
			sql = "INSERT INTO memberBoard VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, sysdate)";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, b_num);
			ps.setString(2, dto.getBoard_id());
			ps.setString(3, dto.getBoard_subject());
			ps.setString(4, dto.getBoard_content());
			ps.setString(5, dto.getBoard_file());
			ps.setInt(6, b_num); //댓글을 쓰기 위한 그룹 번호
			ps.setInt(7, 0); //댓글이 없으니 0
			ps.setInt(8, 0);
			ps.setInt(9, 0);
			succ = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("boardInsert() Exception!!!");
		} finally {
			dbClose();
		}
		return succ;
	} //boardInsert()
	
	//등록된 글의 총 개수
	public int getListCount() {
		conn = getConn();
		String sql = "SELECT COUNT(*) FROM memberBoard";
		//NULL이 들어갈 수 있는 필드도 있으므로 모든 필드를 센 다음에 가장 많이 나온 필드를 기준으로 한다.
		int listCount = 0;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			if(rs.next()) {
				listCount = rs.getInt(1);	//board_num 필드는 NULL값이 들어올 수 없으니 board_num을 가져온다.
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("getListCount() Exception!!!");
		} finally {
			dbClose();
		}
		return listCount;
	} //getListCount()
	
	//전체 글 목록 조회(Feat : 페이징 
	public ArrayList<BoardDTO> getBoardList(int page, int limit) {
		conn = getConn();
		String sql = "SELECT * FROM";
		sql += " (SELECT ROWNUM rnum, board_num, board_id,";
		sql	+= " board_subject, board_content, board_file, board_re_ref,";
		sql += " board_re_lev, board_re_seq, board_readcount, board_date";
		sql	+= " FROM (SELECT * FROM memberBoard ORDER BY";
		sql += " board_re_ref DESC, board_re_seq ASC))";
		sql += "WHERE rnum >= ? and rnum <= ?";
		int startRow = (page - 1) * 10 + 1; //읽기 시작할 rownum
		int endRow = startRow + limit - 1;	//읽을 마지막 rownum
		ArrayList<BoardDTO> list = new ArrayList<>();
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, startRow);
			ps.setInt(2, endRow);
			rs = ps.executeQuery();
			
			while(rs.next()) {
				BoardDTO dto = new BoardDTO();
				dto.setBoard_num(rs.getInt("board_num"));
				dto.setBoard_id(rs.getString("board_id"));
				dto.setBoard_subject(rs.getString("board_subject"));
				dto.setBoard_content(rs.getString("board_content"));
				dto.setBoard_file(rs.getString("board_file"));
				dto.setBoard_re_ref(rs.getInt("board_re_ref"));
				dto.setBoard_re_lev(rs.getInt("board_re_lev"));
				dto.setBoard_re_seq(rs.getInt("board_re_seq"));
				dto.setBoard_readcount(rs.getInt("board_readcount"));
				dto.setBoard_date(rs.getString("board_date"));
				list.add(dto);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("getBoardList() Exception!!!");
		} finally {
			dbClose();
		}
		return list;
	}

	//글 내용 보기
	public BoardDTO getDetail(int board_num) {
		conn = getConn();
		String sql = "SELECT * FROM memberBoard WHERE board_num = ?";
		BoardDTO dto = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, board_num);
			rs = ps.executeQuery();
			
			if(rs.next()) {
				dto = new BoardDTO();
				dto.setBoard_num(rs.getInt("board_num"));
				dto.setBoard_id(rs.getString("board_id"));
				dto.setBoard_subject(rs.getString("board_subject"));
				dto.setBoard_content(rs.getString("board_content"));
				dto.setBoard_file(rs.getString("board_file"));
				dto.setBoard_re_ref(rs.getInt("board_re_ref"));
				dto.setBoard_re_lev(rs.getInt("board_re_lev"));
				dto.setBoard_re_seq(rs.getInt("board_re_seq"));
				dto.setBoard_readcount(rs.getInt("board_readcount"));
				dto.setBoard_date(rs.getString("board_date"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("getDetail() Exception!!!");
		} finally {
			dbClose();
		}
		return dto;
	} //getDetail()
	
	//조회수 증가
	public void readCount(int board_num) {
		conn =getConn();
		String sql = "UPDATE memberBoard SET board_readcount = ";
		sql += "board_readcount + 1 WHERE board_num = ?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, board_num);
			ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("readCount() Excetption!!!");
		} finally {
			dbClose();
		}
	} //readCount()
	
	//작성자 확인
	public boolean isBoardWriter(int board_num, String id) {
		conn = getConn();
		String sql = "SELECT * FROM memberBoard WHERE board_num = ?";
		boolean result = false;
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, board_num);
			rs = ps.executeQuery();
			
			if(rs.next()) {
				if(id.equals(rs.getString("board_id"))) {
					result = true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("isBoardWriter() Exception!!!");
		} finally {
			dbClose();
		}
		return result;
	} //isBoardWriter()

	//글 삭제
	public int boardDelete(int board_num) {
		conn = getConn();
		String sql = "DELETE FROM memberBoard WHERE board_num = ?";
		int succ = 0;
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, board_num);
			succ = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("boardDelete() Exception!!!");
		} finally {
			dbClose();
		}
		return succ;
	} //boardDelete()
	
	//글 수정
	public int boardUpdate(BoardDTO dto) {
		conn = getConn();
		String sql = "UPDATE memberBoard SET board_subject = ?, ";
		sql += "board_content = ? WHERE board_num = ?";
		int succ = 0;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, dto.getBoard_subject());
			ps.setString(2, dto.getBoard_content());
			ps.setInt(3, dto.getBoard_num());
			succ = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("boardUpdate() Exception!!!");
		} finally {
			dbClose();
		}
		return succ;
	} //boardUpdate()

	//답글 등록
	public int boardReply(BoardDTO dto) {
		conn = getConn();
		String board_max_sql = "SELECT MAX(board_num) FROM memberBoard";
		int succ = 0;
		try {
			ps = conn.prepareStatement(board_max_sql);
			rs = ps.executeQuery();
			int num = 0;
			if(rs.next()) {
				num = rs.getInt(1) + 1;
			} else {
				num = 1;
			}
			
			int re_ref = dto.getBoard_re_ref();	//글의 그룹번호
			int re_lev = dto.getBoard_re_lev();	//답글의 깊이
			int re_seq = dto.getBoard_re_seq();	//답글의 순서
			
			String sql = "UPDATE memberBoard SET board_re_seq = board_re_seq + 1";
			sql += "WHERE board_re_ref = ? AND board_re_seq > ?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, re_ref);
			ps.setInt(2, re_seq);
			ps.executeUpdate();
			
			re_seq += 1;
			re_lev += 1;
			
			sql = "INSERT INTO memberBoard(board_num, board_id, board_subject, ";
			sql += "board_content, board_file, board_re_ref, board_re_lev, ";
			sql += "board_re_seq, board_readcount, board_date)";
			sql += " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, SYSDATE)";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, num);
			ps.setString(2, dto.getBoard_id());
			ps.setString(3, dto.getBoard_subject());
			ps.setString(4, dto.getBoard_content());
			ps.setString(5, "");	//답글에는 파일 첨부가 없다.
			ps.setInt(6, re_ref);
			ps.setInt(7, re_lev);
			ps.setInt(8, re_seq);
			ps.setInt(9, 0);	//답글에는 조회수가 없다.
			succ = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("boardReply() Exception!!!");
		} finally {
			dbClose();
		}
		return succ;
	} //boardReply()

	//DB 종료
		public void dbClose() {
			try {
				if(rs != null) rs.close();
				if(ps != null) ps.close();
				if(conn != null) conn.close();
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("dbClose() Exception!!!");
			}
		} //dbClose()
} //class

▲BoardDAO.java

 

<%@page import="java.text.SimpleDateFormat"%>
<%@page import="com.board.study.BoardDTO"%>
<%@page import="java.util.ArrayList"%>
<%@page import="com.member.study.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String id = (String) session.getAttribute("id"); //JSP는 session이 내장 객체라 바로 사용 가능하다.
MemberDAO dao = new MemberDAO();
String member_pw = dao.getMember_pw(id);
Integer nowPage = (Integer)request.getAttribute("page");
Integer maxPage = (Integer)request.getAttribute("maxPage");
Integer startPage = (Integer) request.getAttribute("startPage");
Integer endPage = (Integer) request.getAttribute("endPage");
Integer listCount = (Integer) request.getAttribute("listCount");
ArrayList<BoardDTO> list = new ArrayList<>();
list = (ArrayList<BoardDTO>)request.getAttribute("list");

%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>board list JSP</title>
<script type="text/javascript">
function fnModify(id, member_pw) {
	//alert("id : " + id);
	var pw = prompt("비밀번호를 입력하세요","");
	//alert("member_pw : " + member_pw + "\npw : " + pw);
	//member_pw : dto에 저장되어있던 비밀번호
	//pw : 방금 사용자로부터 입력받은 비밀번호
	if(member_pw == pw) { //맞는 비밀번호를 입력하면 URL이 바뀐다
		//alert("비밀번호 일치합니다.")
		location.href = "memberDetailAction.me?member_id=" + id;
	} else {
		alert("비밀번호가 일치하지 않습니다.");
	}
}
</script>
</head>
<body>
<div align="center">
	<h3>[자유 게시판]</h3>
	<table border= "1">
		<tr align="center";>
			<th>번호</th>
			<th width="200">제목</th>
			<th>작성자</th>
			<th>작성일</th>
			<th>조회수</th>
		</tr>
		<%for(int i = 0; i < list.size(); i++) { 
			BoardDTO dto = list.get(i);%>
			<tr align="center">
				<td><%=dto.getBoard_num() %></td>
				<td align="left">
					<%if(dto.getBoard_re_lev() != 0) {%>
						<%for(int a = 0; a<= dto.getBoard_re_lev(); a++) {%>&nbsp;<%} %>└
					<%} %>
					<a href="boardDetailAction.bo?board_num=<%=dto.getBoard_num() %>"><%=dto.getBoard_subject() %></a>
				</td>
				<td><%=dto.getBoard_id() %></td>
				<td><%=dto.getBoard_date().substring(0, 10) %></td>
				<td><%=dto.getBoard_readcount() %></td>
							
			</tr>
		<%} %>
	
		<tr align="center">
			<td colspan="5">
				<%if(nowPage <= 1) { %>
					[이전]&nbsp;
				<%} else { %>
					<a href="boardList.bo?page=<%=nowPage - 1 %>">[이전]</a>&nbsp;
				<%} %>
				
				<%for(int i = startPage; i <= endPage; i++) { %>
					<%if(i == nowPage) { %>
						[<%=i %>]&nbsp;
					<%} else { %>
						<a href="boardList.bo?page=<%=i %>">[<%=i %>]</a>&nbsp;
					<%} %>
				<%} %>
				
				<%if(nowPage >= maxPage) { %>
					[다음]&nbsp;
				<%} else { %>
					<a href="boardList.bo?page=<%=nowPage + 1 %>">[다음]</a>&nbsp;
				<%} %>
			</td>
		</tr>
	
		<tr align="center">
			<td colspan="5">
				<%if(id != null && id.equals("admin")) { %>
					<input type="button" value="회원 관리" onclick="location.href='memberListAction.me'" />
				<%} %>
				<input type="button" value="로그아웃" onclick="location.href='memberLogout.me'"/>
				<input type="button" value="글쓰기" onclick="location.href='boardWrite.bo'" />
				<input type="button" value="회원 정보 수정" onclick="fnModify('<%=id%>', '<%=member_pw %>')"/>
			</td>
		</tr>
	</table>
</div>
</body>
</html>

▲board_list.jsp

반응형