ReplyBoard 폴더에 구현.
ReplyBoard > List.jsp
<%@page import="utils.BoardPage"%>
<%@page import="model1.board.BoardDAO"%>
<%@page import="model1.board.BoardDTO"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
// DB에 연결
BoardDAO dao = new BoardDAO(application);
// form에서 액션 속성 생략 -> 자기 자신 페이지를 파라매터로 받는다.
String searchField = request.getParameter("searchField");
String searchWord = request.getParameter("searchWord");
Map<String, Object> param = new HashMap<>();
// 검색조건으로 검색하려 할때
if (searchWord != null) {
param.put("searchField", searchField);
param.put("searchWord", searchWord);
}
// 전체 개수 구하기 selectCount()
// 검색 했을 때 개수 dao.selectCount(param)
// boardLists 에 DTO의 정보가 들어있다.
int totalCount = dao.selectCount(param);
int pageSize = Integer.parseInt(application.getInitParameter("POSTS_PER_PAGE"));
int blockPage = Integer.parseInt(application.getInitParameter("PAGES_PER_BLOCK"));
int totalPage = (int) Math.ceil( (double)totalCount / pageSize );
// 페이지 번호를 관리하는 변수
int pageNum = 1;
// 페이지 번호를 다른 걸로 선택하면 그 다른 페이지 번호를 받아온다
String pageTemp = request.getParameter("pageNum");
if (pageTemp != null && !pageTemp.equals("")){
pageNum = Integer.parseInt(pageTemp);
}
// 게시물의 시작번호와 끝 번호 구하기
int start = (pageNum - 1) * pageSize + 1;
int end = pageNum * pageSize;
param.put("start", start);
param.put("end", end);
/* List<BoardDTO> boardLists = dao.selectList(param); */
List<BoardDTO> boardLists = dao.selectListPage(param);
dao.close();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:include page="../Common/Link.jsp" />
<h2>목록 보기(List)</h2>
<!-- 폼태그에 action 속성이 생략되면 자신의 현재 페이지를 요청한다. (List.jsp)-->
<form method="get">
<table border="1" width="90%">
<tr>
<td align="center">
<select name="searchField">
<option value="title">제목</option>
<option value="content">내용</option>
</select>
<input type="text" name="searchWord" />
<input type="submit" value="검색하기" />
</td>
</tr>
</table>
</form>
<table border="1" width="90%">
<tr>
<th width="10%">번호</th>
<th width="50%">제목</th>
<th width="15%">작성자</th>
<th width="10%">조회수</th>
<th width="15%">작성일</th>
</tr>
<!-- 게시물이 없을 떄 -->
<% if (boardLists.isEmpty()) {%>
<tr>
<td colspan="5" align="center">등록된 게시물이 없습니다^^*</td>
</tr>
<% }else{
int virtualNum = totalCount - (pageNum - 1) * pageSize;
for(BoardDTO dto : boardLists){
// virtualNum = totalCount--;
%>
<!-- 게시물이 있을 때 -->
<tr align="center">
<!-- DTO에서 쓴 이름과 같게 -->
<%-- <td><%= dto.getNum() %></td> --%>
<td><%= virtualNum-- %></td>
<td>
<a href="View.jsp?num=<%= dto.getNum() %>"> <%= dto.getTitle() %> </a>
</td>
<td><%= dto.getId() %></td>
<td><%= dto.getVisitcount() %></td>
<td><%= dto.getPostDate() %></td>
</tr>
<%
} // for문
} // if else문
%>
</table>
<table border="1" width="90%">
<tr align="center">
<td>
<!-- [첫번째 페이지] [이전 블럭] [1] [2] [3] [4] [5] [다음 블럭] [마지막 페이지] -->
<!-- request.getRequestURI()로 주소값을 가지고 올 수 있다 -->
<%= BoardPage.pagingStr(totalCount, pageSize, blockPage, pageNum, request.getRequestURI()) %>
</td>
<td align="right">
<button type="button" onclick="location.href='write.jsp'">글쓰기</button>
</td>
</tr>
</table>
</body>
</html>
ReplyBoard > View.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="./IsLoggedIn.jsp"%>
<%@ page import="model1.board.BoardDTO"%>
<%@ page import="model1.board.BoardDAO"%>
<%@ page import="model1.replay.ReplyDAO"%>
<%@ page import="model1.replay.ReplyDTO"%>
<%@ page import="java.util.List"%>
<%
String num = request.getParameter("num");
BoardDAO dao = new BoardDAO(application);
ReplyDAO replyDAO = new ReplyDAO(application);
// 글에 대한 상세보기 -> 조회수 증가 처리
dao.updateVisitCount(num);
// 상세정보 보기 (원글 정보)
BoardDTO dto = dao.selectView(num);
List<ReplyDTO> replyLists = replyDAO.selectReply(num);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시글 상세보기</title>
<script>
function deletePost() {
let confirmed = confirm("정말로 삭제하시겠습니까?");
if (confirmed) {
let form = document.writeFrm;
form.method = "post";
form.action = "DeleteProcess.jsp";
form.submit();
}
}
function validateForm(form) {
if (form.replycontent.value == "") {
alert("댓글 내용을 입력하세요.");
form.replycontent.focus();
return false;
}
}
</script>
</head>
<body>
<h2>회원제 게시판 - 상세보기(View)</h2>
<form name="writeFrm">
<input type="hidden" name="num" value="<%=num%>">
<table border="1" width="90%">
<tr>
<td>번호</td>
<td><%=dto.getNum()%></td>
<td>작성자</td>
<td><%=dto.getName()%></td>
</tr>
<tr>
<td>작성일</td>
<td><%=dto.getPostDate()%></td>
<td>조회수</td>
<td><%=dto.getVisitcount()%></td>
</tr>
<tr>
<td>제목</td>
<td colspan="3"><%=dto.getTitle()%></td>
</tr>
<tr>
<td>내용</td>
<td colspan="3" height="100px">
<%=dto.getContent().replace("\r\n", "<br/>")%></td>
</tr>
<tr>
<td colspan="4" align="center">
<% if (session.getAttribute("UserId") != null && session.getAttribute("UserId").toString().equals(dto.getId())) { %>
<button type="button" onclick="location.href = 'Edit.jsp?num=<%=dto.getNum()%>'">수정하기</button>
<button type="button" onclick="deletePost()">삭제하기</button>
<% } %>
<button type="button" onclick="location.href = 'List.jsp'">목록보기</button>
</td>
</tr>
</table>
</form>
<p>댓글</p>
<table border="1" width="90%">
<% if (replyLists.isEmpty()) { %>
<tr>
<td colspan="5" align="center">등록된 댓글이 없습니다^^*</td>
</tr>
<% } else { %>
<tr>
<th width="10%">번호</th>
<th width="50%">댓글내용</th>
<th width="15%">작성자</th>
<th width="20%">날짜</th>
<th width="5%"></th>
</tr>
<% for (ReplyDTO rDto : replyLists) { %>
<tr align="center">
<td><%= rDto.getReplyno() %></td>
<td><%= rDto.getReplycomment() %></td>
<td><%= rDto.getId() %></td>
<td><%= rDto.getRegidate() %></td>
<td>
<% if (session.getAttribute("UserId") != null && session.getAttribute("UserId").toString().equals(rDto.getId())) { %>
<button type="button" onclick="location.href='ReplyEdit.jsp?replyno=<%=rDto.getReplyno()%>&num=<%=num%>'">수정</button>
<button type="button" onclick="location.href='ReplyDelete.jsp?replyno=<%=rDto.getReplyno()%>&num=<%=num%>'">삭제</button>
<% } %>
</td>
</tr>
<% } %>
<% } %>
</table>
<h3>회원제 게시판 - 댓글(Reply)</h3>
<form name="WriteFrm" method="post" action="ReplyProcess.jsp" onsubmit="return validateForm(this)">
<input type="hidden" name="num" value="<%=dto.getNum() %>">
<table border="1" width="90%">
<tr>
<td>댓글 내용</td>
<td><textarea name="replycontent" style="width: 90%;"></textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit">작성완료</button>
<button type="reset">다시입력</button>
</td>
</tr>
</table>
</form>
</body>
</html>
IsLoggedIn.jsp
<%@page import="utils.JSFunction"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- 로그인 유무를 판단 -->
<%
if (session.getAttribute("UserId") == null){
JSFunction.alertLocation("로그인 후 이용해주세요.", "../Session/LoginForm.jsp", out);
return;
}
%>
write.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- 공통관심사항 -->
<%@ include file ="./IsLoggedIn.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- 유효성 검사 -->
<script>
function validateForm(form){
if (form.title.value == ""){
alert("제목을 입력하세요");
form.title.focus();
return false;
}
if (form.content.value == ""){
alert("내용을 입력하세요");
form.content.focus();
return false;
}
}
</script>
</head>
<body>
<jsp:include page="../Common/Link.jsp" />
<h2>회원제 게시판 - 글쓰기(Write)</h2>
<form name="writeFrm" method="post" action="WriteProcess.jsp"
onsubmit="return validateForm(this);">
<table bordar="1" width="90%">
<tr>
<td>제목</td>
<td><input type="text" name="title" style="width: 90%;" /></td>
</tr>
<tr>
<td>내용</td>
<td><textarea name="content" style="width: 90%; height: 100px;"></textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit">작성 완료</button>
<button type="reset">다시 입력</button>
<button type="button" onclick="location.href='List.jsp';">
목록 보기</button>
</td>
</tr>
</table>
</form>
</body>
</html>
WriteProcess.jsp
<%@page import="model1.board.BoardDTO"%>
<%@page import="model1.board.BoardDAO"%>
<%@ include file ="./IsLoggedIn.jsp"%>
<%@page import="utils.JSFunction"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
// 타이틀과 컨텐츠를 파라메터로 받는다.
String title = request.getParameter("title");
String content = request.getParameter("content");
// DTO의 데이터를 묶어서 DAO로 보낸다.
// 서버 -> DTO -> DAO -> DB
// 서버 <- DTO <- DAO
BoardDTO dto = new BoardDTO();
dto.setTitle(title);
dto.setContent(content);
dto.setId((String)session.getAttribute("UserId"));
// DAO에 데이터를 삽인하는 기능 추가
// DB에 연결
BoardDAO dao = new BoardDAO(application);
int result = dao.insertWrite(dto);
// 페이징 기능을 위한 데이터 집어넣기
// 한번만 실행해야 한다.
/* for(int i = 1; i <= 100; i++){
dto.setTitle(title + "-" + i);
dao.insertWrite(dto);
} */
dao.close();
if(result > 0){
// 성공했을 때 페이지 이동
response.sendRedirect("List.jsp");
}else{
// 실패 시 이전 페이지로
JSFunction.alertBack("글쓰기에 실패하였습니다.", out);
}
%>
Edit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.board.BoardDAO"%>
<%@ page import="model1.board.BoardDTO"%>
<%@ include file="./IsLoggedIn.jsp"%>
<%
String num = request.getParameter("num");
BoardDAO dao = new BoardDAO(application);
BoardDTO dto = dao.selectView(num);
String sessionId = session.getAttribute("UserId").toString();
System.out.println(sessionId);
System.out.println(dto.getId());
System.out.println(dto.getNum());
if(!sessionId.equals(dto.getId())){
JSFunction.alertBack("작성자 본인만 수정할 수 있습니다.", out);
return;
}
dao.close();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
//validateForm()
function validateForm(form) {
if (form.title.value == "") {
alert("제목을 입력하세요.");
form.title.focus();
return false;
}
if (form.content.value == "") {
alert("내용을 입력하세요.");
form.content.focus();
return false;
}
}
</script>
</head>
<body>
<%@ include file ="./IsLoggedIn.jsp"%>
<h2>회원제 게시판 - 수정하기(Edit)</h2>
<form name="writeFrm" method="post" action="EditProcess.jsp" onsubmit="return validateForm(this);">
<!-- 값을 추가적으로 지정해서 넘길 때 hidden form -->
<!-- num, title, content 가 넘어간다. -->
<input type="hidden" name="num" value="<%=dto.getNum() %>">
<table border="1" width="90%">
<tr>
<td>제목</td>
<td>
<input type="text" name="title" value="<%= dto.getTitle() %>" />
</td>
</tr>
<tr>
<td>내용</td>
<td>
<textarea name="content" style="width: 90%; height: 100px;"><%=dto.getContent() %></textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit">작성완료</button>
<button type="reset">다시입력</button>
<button type="button" onclick="location.href='List.jsp'">목록보기</button>
</td>
</tr>
</table>
</form>
</body>
</html>
EditProcess.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.board.BoardDAO"%>
<%@ page import="model1.board.BoardDTO"%>
<%@ page import="utils.JSFunction" %>
<%@ include file="./IsLoggedIn.jsp"%>
<%
String num = request.getParameter("num");
String title = request.getParameter("title");
String content = request.getParameter("content");
BoardDTO dto = new BoardDTO();
dto.setNum(num);
dto.setTitle(title);
dto.setContent(content);
BoardDAO dao = new BoardDAO(application);
int result = dao.updateEdit(dto);
dao.close();
/* 글 올리기 성공했을 때는 상세보기 화면, 실패하면 수정하기 */
if (result > 0){
/* View 페이지에서 어떤 글을 수정해야 하는지 알기 위해 */
response.sendRedirect("View.jsp?num=" + dto.getNum());
}else{
JSFunction.alertBack("수정하기에 실패했습니다", out);
}
%>
ReplyProcess.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.replay.ReplyDAO"%>
<%@ page import="model1.replay.ReplyDTO"%>
<%@ page import="utils.JSFunction" %>
<%@ include file="./IsLoggedIn.jsp"%>
<%
String comment = request.getParameter("replycontent");
String num = request.getParameter("num");
String sessionId = (String)session.getAttribute("UserId");
ReplyDTO rDto = new ReplyDTO();
rDto.setNum(num);
rDto.setReplycomment(comment);
rDto.setId(sessionId);
ReplyDAO dao = new ReplyDAO(application);
int result = dao.insertReply(rDto);
dao.close();
if (result > 0){
response.sendRedirect("View.jsp?num=" + num);
}else {
JSFunction.alertBack("댓글 쓰기에 실패했습니다.", out);
}
%>
ReplyEdit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.replay.ReplyDAO"%>
<%@ page import="model1.replay.ReplyDTO"%>
<%@ include file="./IsLoggedIn.jsp"%>
<%
String replyno = request.getParameter("replyno");
String num = request.getParameter("num");
ReplyDTO rDto = new ReplyDTO();
ReplyDAO rDao = new ReplyDAO(application);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
//validateForm()
function validateForm(form) {
if (form.replycontent.value == "") {
alert("댓글 내용을 입력하세요.");
form.replycontent.focus();
return false;
}
}
</script>
</head>
<body>
<h2>댓글 수정</h2>
<form name="editReplyFrm" method="post" action="ReplyEditProcess.jsp" onsubmit="return validateForm(this)">
<input type="hidden" name="replyno" value="<%=replyno%>">
<input type="hidden" name="num" value="<%=num%>">
<table border="1" width="90%">
<tr>
<td>댓글 내용</td>
<td><textarea name="replycontent" style="width: 90%;"><%=rDto.getReplycomment()%></textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit">수정완료</button>
<button type="button" onclick="location.href='View.jsp?num=<%=num%>'">취소</button>
</td>
</tr>
</table>
</form>
</body>
</html>
ReplyEditProcess.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="./IsLoggedIn.jsp"%>
<%@ page import="model1.replay.ReplyDAO"%>
<%@ page import="model1.replay.ReplyDTO"%>
<%
String replyno = request.getParameter("replyno");
String num = request.getParameter("num");
String replycontent = request.getParameter("replycontent");
ReplyDTO rDto = new ReplyDTO();
rDto.setReplyno(replyno);
rDto.setReplycomment(replycontent);
ReplyDAO rDao = new ReplyDAO(application);
int updateResult = rDao.updateReply(rDto);
if (updateResult > 0) {
response.sendRedirect("View.jsp?num=" + num);
} else {
out.println("<script>");
out.println("alert('댓글 수정에 실패했습니다.');");
out.println("history.back();");
out.println("</script>");
}
%>
ReplyDelete.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.replay.ReplyDAO"%>
<%@ page import="model1.replay.ReplyDTO"%>
<%@ include file="./IsLoggedIn.jsp"%>
<%
String replyno = request.getParameter("replyno");
String num = request.getParameter("num");
ReplyDTO rDto = new ReplyDTO();
rDto.setReplyno(replyno);
// System.out.println("replyno : " + dto.getReplyno());
ReplyDAO rDao = new ReplyDAO(application);
int result = rDao.deleteReply(rDto);
// String sessionId = session.getAttribute("UserId").toString();
// System.out.println(sessionId);
// System.out.println(dto.getId());
// System.out.println(dto.getNum());
if (result > 0) {
JSFunction.alertLocation("댓글이 삭제되었습니다.", "View.jsp?num=" + num, out);
} else {
JSFunction.alertBack("삭제에 실패했습니다.", out);
}
rDao.close();
%>
DeleteProcess.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.board.BoardDAO"%>
<%@ page import="model1.board.BoardDTO"%>
<%@ page import="utils.JSFunction" %>
<%@ include file="./IsLoggedIn.jsp"%>
<%
String num = request.getParameter("num");
BoardDTO dto = new BoardDTO();
BoardDAO dao = new BoardDAO(application);
dto = dao.selectView(num);
String sessionId = session.getAttribute("UserId").toString();
// 글을 작성한 사람인지 아닌지. 글을 작성한 사람만 게시글을 삭제할 수 있다.
if (sessionId.equals(dto.getId())){
// 본인 인증 성공, 삭제 처리
dto.setNum(num);
int result = dao.deletePost(dto);
dao.close();
if (result > 0) {
// 삭제 성공
JSFunction.alertLocation("삭제되었습니다", "List.jsp", out);
}else{
// 삭제 실패 -> 상세 페이지 화면
JSFunction.alertBack("삭제에 실패했습니다.", out);
}
}else{
// 본인 인증 실패
JSFunction.alertBack("본인만 삭제할 수 있습니다.", out);
return;}
%>
ReplyDTO
package model1.replay;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ReplyDTO {
// 컬럼명
private String replyno;
private String replycomment;
private String id;
private String regidate;
private String num;
}
ReplyDAO
package model1.replay;
import java.util.ArrayList;
import java.util.List;
import common.JDBConnect;
import jakarta.servlet.ServletContext;
import model1.board.BoardDTO;
public class ReplyDAO extends JDBConnect {
public ReplyDAO (ServletContext application) {
super(application);
}
public List<ReplyDTO> selectReply(String num){
List<ReplyDTO> replybbs = new ArrayList();
String query = " select replyno, replycomment, r.id, r.regidate, r.num "
+ " from reply r inner join board b "
+ " on r.num = b.num "
+ " where r.num = ? "
+ " order by replyno asc ";
try {
psmt = con.prepareStatement(query);
psmt.setString(1, num);
rs = psmt.executeQuery();
while(rs.next()) {
ReplyDTO dto = new ReplyDTO();
dto.setReplyno(rs.getString(1));
dto.setReplycomment(rs.getString(2));
dto.setId(rs.getString(3));
dto.setRegidate(rs.getString(4));
dto.setNum(rs.getString(5));
replybbs.add(dto);
}
}catch (Exception e) {
e.printStackTrace();
}
return replybbs;
}
public int insertReply(ReplyDTO dto) {
int result = 0;
String query = " insert into reply "
+ " (replyno, replycomment, id, num) "
+ " values (seq_board_num.nextval,?, ?, ?)";
try {
psmt = con.prepareStatement(query);
psmt.setString(1, dto.getReplycomment());
psmt.setString(2, dto.getId());
psmt.setString(3, dto.getNum());
result = psmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
// 댓글 수정
public int updateReply(ReplyDTO dto) {
int result = 0;
String query = " update reply " + " set replycomment = ? " + " where replyno = ? ";
try {
psmt = con.prepareStatement(query);
psmt.setString(1, dto.getReplycomment());
psmt.setString(2, dto.getReplyno());
result = psmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
// 댓글 삭제
public int deleteReply(ReplyDTO dto) {
System.out.println("replyno : " + dto.getReplyno());
int result = 0;
String query = " delete from reply where replyno = ? ";
try {
psmt = con.prepareStatement(query);
psmt.setString(1, dto.getReplyno());
// 댓글 어떻게 판단할지
result = psmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
댓글작성자에게만 수정, 삭제 버튼이 보이고, 댓글 작성자는 정상적으로 수정, 삭제를 할 수 있다.
코드를 구현하며 잘 안됐던, 어려웠던 부분에 대한 노트 추가)