JAVA

Spring:댓글

docc 2021. 7. 26. 23:06

Comment 댓글

>> Comment<VO>

public class Comment {
	private int no;
	private String contents;
	private Date wdate;
	private Member member;
	private Board board;
//getter,setter 부분
}

>> ICommentDAO

public interface ICommentDAO {

	void save(Comment comment);
	List<Comment> selectByBoardNo(int 게시물번호, int size, RefInteger totalSize);
}

>> MemberDAO ( 메서드 추가 )

	//member 이름만 갖고오기(다가져올필요 없으니까)
    @Override
	public String findName(int no) {
		
		String name = null;
		
		try {

			Connection c = ConnectionUtil.getConnection();

			Statement 명령전달자 = c.createStatement();

			
			// 선택한 게시물 가져오기
			String 수집SQL = String.format("select name from member where no = %d",no);
			ResultSet 수집된표관리자 = 명령전달자.executeQuery(수집SQL);

			if(수집된표관리자.next()) {

				name = 수집된표관리자.getString("name");

			}

			수집된표관리자.close();
			명령전달자.close();
			c.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return name;
	}

>> CommentDAO

	@Override
	public List<Comment> selectByBoardNo(int 게시물번호, int size/* 수집할 댓글수 */, RefInteger totalSize/* 해당 게시물의 총댓글수 */) {
		ArrayList<Comment> comments = null;
		Connection c = null;
		PreparedStatement ps = null;
		try {

			c = ConnectionUtil.getConnection();
			ps = c.prepareStatement("select * from comment where board_no=? order by wdate desc limit 0,?");
			ps.setInt(1,게시물번호);
			ps.setInt(2,size);
			ResultSet set = ps.executeQuery();
			
			while(set.next()) {
				int no = set.getInt("no");
				String contents = set.getString("contents");
				Date wdate = set.getDate("wdate");
				
				int 작성자번호 = set.getInt("writer");
				String 댓글작성자성명 = memberDAO.findNameByNo(set.getInt("writer"));
				Member member = new Member();
				member.setNo(작성자번호);
				member.setName(댓글작성자성명);

				Comment comment = new Comment();
				comment.setNo(no);
				comment.setContents(contents);
				comment.setWdate(wdate);
				comment.setWriter(member);
				
				comments = new ArrayList<Comment>();
				comments.add(comment);
			}
			set.close();
			
			ps = c.prepareStatement("select count(*) from comment where board_no=?");
			ps.setInt(1,게시물번호);
			
			ResultSet set2 = ps.executeQuery();
			set2.next();
			//열의 순서대로 숫자를 넣어도 가져옴.
			totalSize.value = set2.getInt(1);
			
			set2.close();
			ps.close();
			c.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return comments;
	}

>> 게시물컨트롤

	@PostMapping("board/comments/{no}")
	public ModelAndView 게시물댓글을출력하다(@PathVariable int no, int size,HttpSession session) {
		
		RefInteger totalSize = new RefInteger();
		List<Comment> comments = commentDAO.selectByBoardNo(no, size, totalSize);
		
		ModelAndView mv = new ModelAndView();
		mv.addObject("totalSize", totalSize.value);
		mv.addObject("size", size);
		mv.addObject("comments", comments);
		//로그인한 회원의 번호, 로그인하지 않은 경우 null
        // 댓글을 본인이 달았는지 comment.writer.no 와 비교하여 삭제버튼유무를 가릴려고
		mv.addObject("member_no",session.getAttribute("no"));
		mv.setViewName("/board/댓글창");
		
		return mv;
		
	}
​