HTML

240122 HTML 홈페이지

코딩하는딩굴 2024. 1. 22. 13:52

오늘은 댓글 달기 ~

 

먼저 댓글 다는 항목 생성

<!-- 댓글 쓰는 창을 여기에 작성 / 내용, 작성자, 어느 글 -->
<c:if test="${sessionScope.mid ne null }">
  <div class="comment-write">
    <div class="comment-form">
      <textarea id="commentcontent" name="commentcontent"></textarea>
      <button id="comment-btn">작성</button>
    </div>
  </div>
</c:if>
<!-- 댓글 출력 창 -->
<div class="comments">
  <c:forEach items="${commentList }" var="comm">
    <div class="comment">
      <div class="chead">
        <div class="cname">${comm.mno }</div>
        <div class="cdate">${comm.cdate }</div>
      </div>
    <div class="ccomment">${comm.ccomment }</div>
    </div>
  </c:forEach>
</div>

 

댓글을 작성 후 보낼 때 제이쿼리로 작성

<script type="text/javascript">
$(document).ready(function(){
  // alert("제이쿼리 준비완료");
  
  $("#comment-btn").click(function(){
    let content = $("#commentcontent").val();
    let bno = ${detail.no};
    // alert(content + " -> 내용\n" + "글번호 : " + bno);
    // 가상 form 만들기, 가상의 html 을 만들어서 전송 = 동적 생성
    // 전송하기, 길이가 0 이면 전송하지 않기
    if (content.length < 1) {
      alert("글 내용을 작성하세여");
      $("#commentcontent").focus();
      // 전송을 하지 않아 return false; 가 필요하지 않음
    } else {
      let form = $('<form></form>');
      form.attr('name', 'form');
      form.attr('method','post');
      form.attr('action','./comment');
      
      form.append($('<input/>', {type:'hidden', name:'commentcontent', value:content})); // json
      form.append($('<input/>', {type:'hidden', name:'no', value:bno}));
      
      form.appendTo('body');
      form.submit();
      
      /* let form = document.createElement('form');
      form.name = "form";
      form.method = "post";
      form.action = "./comment";
      // 붙이기
      let text = document.createElement('input');
      text.setAttribute("type", "hidden");
      text.setAttribute("name", "commentcontent");
      text.setAttribute("value", content);
      // 붙이기
      let no = document.createElement('input');
      no.setAttribute("type", "hidden");
      no.setAttribute("name", "no");
      no.setAttribute("value", num); // ${detail.no} 도 사용 가능
      // form 에 붙이기
      form.appendChild("text");
      form.appendChild("no");
      // 전송하기
      document.body.appendChild(form);
      form.submit(); */
    }
  });
});

 

제이쿼리를 사용하기 위해 문장 필요

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.7.1.min.js"></script>

 

보낼 때 post 방식으로 보내기 때문에 comment Sevlet 을 생성하여

post 쪽에 값을 받고 저장하는 역할 수행

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    HttpSession session = request.getSession();
    // 오는 값 받기
    if (session.getAttribute("mid") == null
        && Util.intCheck(request.getParameter("bno"))
        && request.getParameter("content") != null) {
      response.sendRedirect("./login");
    } else {
      String commentContent = request.getParameter("commentcontent");
      String bno = request.getParameter("no");
      // System.out.println("댓글 : " + commentContent + " 글번호 : " + bno);

      // 저장하기
      CommentDAO dao = new CommentDAO();
      CommentDTO dto = new CommentDTO();
      dto.setBoard_no(Util.str2Int(bno));
      dto.setCcomment(commentContent);
      dto.setMid((String) session.getAttribute("mid"));

      dao.commentWrite(dto);

      // 테스트
      response.sendRedirect("./detail?no=" + bno);
    }
  }

 

댓글을 저장하기 위해 CommentDAO, DTO 생성

  public int commentWrite(CommentDTO dto) {
    Connection conn = dbConn.getConn();
    PreparedStatement pstmt = null;
    int result = 0;
    String sql = "INSERT INTO comment(board_no, mno, ccomment) values (?,(SELECT mno FROM c23c_26.member WHERE mid=?),?)";
    
    try {
      pstmt = conn.prepareStatement(sql);
      pstmt.setInt(1, dto.getBoard_no());
      // System.out.println(dto.getBoard_no());
      pstmt.setString(2, dto.getMid());
      // System.out.println(dto.getMid());
      pstmt.setString(3, dto.getCcomment());
      // System.out.println(dto.getCcomment());
      result = pstmt.executeUpdate();
    } catch (SQLException e) {
      e.printStackTrace();
      System.out.println("CommentDAO - comment 에러");
    } finally {
      close(conn, pstmt, null);
    }
    return result;
  }
  
  public List<CommentDTO> commentList(int no) {
    Connection conn = dbConn.getConn();
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    List<CommentDTO> list = null;
    String sql = "SELECT * FROM comment WHERE board_no=?";
        // + " and mno=(SELECT mno FROM c23c_26.member WHERE mid=?)";
    
    try {
      pstmt = conn.prepareStatement(sql);
      pstmt.setInt(1, no);
      // pstmt.setString(1, dto.getMid());
      rs = pstmt.executeQuery();
      list = new ArrayList<CommentDTO>();
      while (rs.next()) {
        CommentDTO dto = new CommentDTO();
        dto.setCno(rs.getInt("cno"));
        dto.setBoard_no(rs.getInt("board_no"));
        dto.setCcomment(rs.getString("ccomment"));
        dto.setCdate(rs.getString("cdate"));
        dto.setClike(rs.getInt("clike"));
        dto.setMno(rs.getInt("mno"));
        list.add(dto);
      }
    } catch (SQLException e) {
      e.printStackTrace();
      System.out.println("CommentDAO - commentList 에러");
    } finally {
      close(conn, pstmt, rs);
    }
    return list;
  }

 

DTO 에는 DB 에 포함된 내용과 닉네임 등 댓글 표현에 필요한 사항 작성

public class CommentDTO{
  private int cno, board_no, mno, clike;
  private String ccomment, cdate, mname, mid;
  
  public int getCno() {
    return cno;
  }
  public void setCno(int cno) {
    this.cno = cno;
  }
  public int getBoard_no() {
    return board_no;
  }
  public void setBoard_no(int board_no) {
    this.board_no = board_no;
  }
  public int getMno() {
    return mno;
  }
  public void setMno(int mno) {
    this.mno = mno;
  }
  public int getClike() {
    return clike;
  }
  public void setClike(int clike) {
    this.clike = clike;
  }
  public String getCcomment() {
    return ccomment;
  }
  public void setCcomment(String ccomment) {
    this.ccomment = ccomment;
  }
  public String getCdate() {
    return cdate;
  }
  public void setCdate(String cdate) {
    this.cdate = cdate;
  }
  public String getMname() {
    return mname;
  }
  public void setMname(String mname) {
    this.mname = mname;
  }
  public String getMid() {
    return mid;
  }
  public void setMid(String mid) {
    this.mid = mid;
  }
}

 

댓글 작성은 로그인 한 사람만 댓글 작성 창 나오게 설정하고

값을 받을 때에도 한번 더 로그인 한 사용자가 있는지 체크

 

Servlet 을 보면 알 수 있지만, 댓글을 작성하면 그 게시물을 다시 한번 로드하여 새로고침

 

자신이 단 댓글에 수정, 삭제 버튼 표시하기

-> 글 수정삭제 로직 비슷하게 끌고옴

<div class="cname">${comm.mname } 님
  <c:if test="${comm.mid eq sessionScope.mid && sessionScope.mname ne null }">
    <img alt="삭제" src="./image/delete.png" onclick="commentDel(${comm.cno})">
    <img alt="수정" src="./image/edit.png" onclick="commentUpdate(${comm.cno})">
  </c:if>
</div>

 

해서 자바스크립트에 commentDel, commentUpdate 추가

function commentDel(cno) {
  if (confirm("댓글 삭제")) {
    location.href="./commentDel?no=${detail.no}&cno=" + cno;
  }
}

function commentUpdate(cno) {
  if (confirm("댓글 수정")) {
    location.href="./commentUpdate?no=${detail.no}&cno=" + cno;
  }
}

 

다른 js 파일에 넣었더니 안돼서..

html 밑에 작성..

 

CommentDel Servlet 생성

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession();
    if (session.getAttribute("mid") != null
        && request.getParameter("no") != null
        && request.getParameter("cno") != null) {
      CommentDTO dto = new CommentDTO();
      
      dto.setMid((String) session.getAttribute("mid"));
      dto.setCno(Util.str2Int(request.getParameter("cno")));
      
      CommentDAO dao = new CommentDAO();
      int result = dao.commentDelete(dto);
      
      if (result == 1) {
        response.sendRedirect("./detail?no=" + request.getParameter("no"));
      } else {
        response.sendRedirect("./error.jsp");
      }
    } else {
      response.sendRedirect("./error.jsp");
    }
  }

 

여기도 ENUM 으로 0, 1 값 중 하나로 둔 다음에

실제 DB 에 삭제 대신, 노출이 안되게 값 변경