카테고리 없음

부트캠프 60일차 (model2의 Comment부분)

동곤일상 2025. 4. 28. 11:23
반응형

 

1) Comment(댓글)

1-1) 댓글테이블생성

1-2)Comment테이블생성

1-3) view/board/info.jsp에 댓글부분 추가

1-4) controller 및 Dao , Mapper 생성


1) Comment(댓글)

 

1-1 ) 댓글(comment) 테이블생성

create table comment(
	num int references board(num) ,
	seq int,
	writer varchar(30),
	content varchar(2000),
	regdate datetime,
	primary key (num,seq)
);

 

 

1-2) Comment클래스생성

package model.comment;

import java.util.Date;

public class Comment {
	private int num;
	private int seq;
	private String writer;
	private String content;
	private Date regdate;
	//setter,getter,toString()
  }

 

 


1-3 ) view/board/info.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>
<html>
<head>
<meta charset="UTF-8">
<title>게시물상세보기</title>
</head>
<body>
<h2 class="">${boardName}</h2>
<table class="table">
<tr><th width="20%">글쓴이</th> <!-- Controller에서 b속성(boarder객체)를 넘겼음 -->
<td width="80%" style="text-align:left">${b.writer}</td></tr>
<%-- ${b.xxx} : b(board)에 getxx프로퍼티 --%>
<tr><th>제목</th><td style="text-align:left">${b.title}</td></tr>
<tr><th>내용</th><td><table style="width:100%; height:250px;">
<tr><td style="border-width:0px; vertical-align:top; text-align:left; margin:0px; padding:0px;">
${b.content}</td></tr></table></td></tr>
<tr><th>첨부파일</th>
	<td><c:if test="${empty b.file1}">&nbsp;</c:if>
	<c:if test="${!empty b.file1}">
		<a href="../upload/board/${b.file1}">${b.file1}</a>
	</c:if></td></tr>
<tr><td colspan="2" class="w3-center">
	<a href="replyForm?num=${b.num}">[답변]</a>
	<a href="updateForm?num=${b.num}">[수정]</a>
	<a href="deleteForm?num=${b.num}">[삭제]</a>
	<a href="list?boardid=${b.boardid}">[목록]</a>
</td></tr></table>


<%--댓글 등록,조회ㅡ삭제 --%>
<span id="comment"></span>
<form action="comment" method="post">
<input type="hidden" name="num" value="${b.num}"><%--게시물번호 --%>
<div class="col-4 text-center">
<p>작성자: <input type="text" name="writer" class="form-control"></p>
</div>
<div class="col-7 text-center">
<p>내용: <input type="text" name="content" class="form-control"></p>
</div>
<div class="col-2 text-center">
<p><button type="submit" class="btn btn-primary">댓글등록</button></p>
</div>
</form>
<div class="contatiner">
<table class="table">
<c:forEach var="c" items="${commlist}">
<tr><td>${c.seq}</td><td>${c.writer}</td>
<td>${c.content}</td>
<td>
<fmt:formatDate value="${c.regdate}" type="both" var="rdate"/>
${rdate}
</td>
<td align="right">
<a class="btn btn-danger" href="commdel?num=${param.num}&seq=${c.seq}">삭제</a>
</td></tr>
</c:forEach>
</table>
</div>

</body>
</html>

 

1-4)controller 및 Dao , Mapper 생성

(BoardController의 info,comment매핑부분)

등록 삭제 기능

@RequestMapping("info")
	public String info(HttpServletRequest request, HttpServletResponse response) {
		int num = Integer.parseInt(request.getParameter("num"));
		String readcnt = request.getParameter("readcnt");
//		String boardid = (String)request.getSession().getAttribute("boardid");
		// b : num 값의 게시물 데이터 저장
		Board b = dao.numSearch(num);
		// readcnt 파라미터의 값이 "f"인 경우 조회수 증가 안함.
		if(readcnt == null || !readcnt.trim().equals("f")) {
			dao.readcntAdd(num); // 조회수 증가
		}
		String boardid = b.getBoardid();
		String boardName = "공지사항";
		if(boardid.equals("2")) {
			boardName = "자유게시판";
		}
		List<Comment> commlist = comdao.list(num);
		request.setAttribute("b",b);
		request.setAttribute("boardName", boardName);
		request.setAttribute("boardid", boardid);
		request.setAttribute("commlist", commlist); // 댓글 목록 view로 전달
		return "board/info";
	}
	
	@RequestMapping("comment")
	public String comment(HttpServletRequest request , 
			HttpServletResponse response) {
		Comment comm = new Comment();
		comm.setNum(Integer.parseInt(request.getParameter("num")));
		comm.setWriter(request.getParameter("writer"));
		comm.setContent(request.getParameter("content"));
		int seq = comdao.maxseq(comm.getNum());
		comm.setSeq(seq+1);
		if(comdao.insert(comm)) {
			return "redirect:info?num="+comm.getNum();
		}
		request.setAttribute("msg", "오류발생(댓글)");
		request.setAttribute("url", "info?num="+comm.getNum()+"&readcnt=f");
		return "alert";
	}
	
	/*
	 * 삭제는 누구든지 가능 (수정필요)
	 * 비밀번호를 입력 or 로그인정보로 판단 필요
	 * 현재는 그냥 기능만구현하는거임
	 */
	@RequestMapping("commdel")
	public String commdel(HttpServletRequest request , 
			HttpServletResponse response) {
		int num = Integer.parseInt(request.getParameter("num"));
		int seq = Integer.parseInt(request.getParameter("seq"));
		String url = "info?num="+num+"&readcnt=f";
		if(comdao.delete(num,seq)) {
			return "redirect:"+url;
		}
		request.setAttribute("msg", "삭제 실패");
		request.setAttribute("url", url);
		return null;
	}

 

/java/model/comment/CommentDao.java

package model.comment;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import model.MyBatisConnection;
import model.mapper.CommentMapper;

public class CommentDao {

	private Class<CommentMapper> cls = CommentMapper.class;
	private Map<String, Object> map = new HashMap<>();
	
	
	public int maxseq(int num) {
		SqlSession session = MyBatisConnection.getConnection();
		try {
			return session.getMapper(cls).maxseq(num);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			MyBatisConnection.close(session);
		}
		return 0;
	}
	
	public boolean insert(Comment comm) {
		SqlSession session = MyBatisConnection.getConnection();
		try {
			map.put("num", comm.getNum());
			map.put("content", comm.getContent());
			map.put("writer", comm.getWriter());
			map.put("seq", comm.getSeq());
			return session.getMapper(cls).insert(comm);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			MyBatisConnection.close(session);
		}
		return false;
	}

	public  List<Comment> list(int num) {
		SqlSession session = MyBatisConnection.getConnection();
		try {
			return session.getMapper(cls).list(num);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			MyBatisConnection.close(session);
		}
		return null;
	}

	public boolean delete(int num, int seq) {
		SqlSession session = MyBatisConnection.getConnection();
		try {
			map.clear();
			map.put("num", num);
			map.put("seq", seq);
			return session.getMapper(cls).delete(map);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			MyBatisConnection.close(session);
		}
		return false;
	}

}

 

CommentMapper

package model.mapper;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import model.comment.Comment;

public interface CommentMapper {

	
	@Select("select IFNULL(MAX(seq),0) from comment where num=#{num}")
	public int maxseq(int num);

	@Insert("insert into comment(num,content,writer,seq,regdate)"
			+ " values(#{num},#{content},"
			+ " #{writer},#{seq},now())")
	public boolean insert(Comment comm);

	
	@Select("select * from comment where num=#{num}")
	 List<Comment> list(int num);

	@Delete("delete from comment where num=#{num} and seq=#{seq}")
	public boolean delete(Map<String, Object> map);

}