detail.jsp

<div class="m-2">
	<c:if test="${sessionScope.principal.id == reply.userId }">
		<i onclick="deleteReply(${reply.id})" class="material-icons">delete</i>
	</c:if>
    </div>
</li>
</c:forEach>

delete 버튼이 나에게만 보이도록 c:if 문으로 userId를 비교함

 

 

boardDetail.js

function deleteReply(id){
	// 세션의 유저의 id와 reply의 userId를 비교해서 같을때만!!
	alert("댓글 아이디 : "+id);
	$.ajax({
		type : "post",
		url : "/blog/reply?cmd=delete&id="+id,
		dataType : "json"
	}).done(function(result) { //  { "statusCode" : 1 }
		if (result.statusCode == 1) {
			console.log(result);
			$("#reply-"+id).remove();
		} else {
			alert("댓글삭제 실패");
		}
	});
}


post 요청을 함, body 데이터는 필요없어서 data, ContentType 은 작성하지 않았음

 

 

 

 

ReplyDao.java

public int deleteById(int id) {
		String sql = "DELETE FROM reply WHERE id = ?";
		Connection conn = DB.getConnection();
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, id);
			int result = pstmt.executeUpdate();
			return result;

		} catch (Exception e) {
			e.printStackTrace();
		} finally { // 무조건 실행
			DB.close(conn, pstmt);
		}
		return -1;
	}

 

 

ReplyService.java

public int 댓글삭제(int id) {
		return replyDao.deleteById(id);
	}

 

 

ReplyController.java

else if(cmd.equals("delete")) {
			int id = Integer.parseInt(request.getParameter("id"));
			int result = replyService.댓글삭제(id);

			CommonRespDto commonDto = new CommonRespDto<>();
			commonDto.setStatusCode(result);  //1, -1

			Gson gson = new Gson();
			String jsonData = gson.toJson(commonDto);
			// { "statusCode" : 1 }
			Script.responseData(response, jsonData);
		}

쿼리스트링에 있는 id값을 id변수에 저장한다.

replyService.댓글삭제 의 return 값을 result 변수에 저장한다.

CommonRespDto<T>{

  int statusCode

  int T data

}

CommonRespDto 객체를 하나 만든다

새로만든 객체의 statusCode 의 값을 result로 set

data는 null 일 것이다.

 

객체를 toJson( Json하고싶은 JAVA Object ) 해서 응답한다. -> { "statusCode" : 1 }

( ajax deleteById 에게 jsonData를 result 로 응답한다. ) (항상 JSON으로 통신해야 함)

boardDetail.js - deleteById()

function deleteReply(id){
	// 세션의 유저의 id와 reply의 userId를 비교해서 같을때만!!
	//alert("댓글 아이디 : "+id);
	$.ajax({
		type : "post",
		url : "/blog/reply?cmd=delete&id="+id,
		dataType : "json"
	}).done(function(result) { //  { "statusCode" : 1 }
		if (result.statusCode == 1) {
			console.log(result);
			$("#reply-"+id).remove();
		} else {
			alert("댓글삭제 실패");
		}
	});
}

Script.responseData()

public static void responseData(HttpServletResponse response, String jsonData) {

		PrintWriter out;
		try {
			out = response.getWriter();
			out.print(jsonData);
			out.flush(); // 버퍼 비우기
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

 

+ Recent posts