티스토리 뷰

 

 

댓글 기능 

 

detail.jsp
자바 스크립트 기능 추가 

 

<div style="text-align: center;">
		<input type="text" id="memberId">
		<input type="text" id="replyContent">
		<button id="btnAdd">작성</button>
	</div>
	<hr>
	<div style="text-align: center;">
		<div id="replies"></div>
	</div>

	<div>
		<br><br><br><br><br><br><br><br><br><br><br><br>
	</div>

	<script type="text/javascript">
		$(document).ready(function(){
			getAllReplies(); // 함수 호출 코드 추가
			
			$('#btnAdd').click(function(){
				let boardId = $('#boardId').val(); // 게시판 번호 데이터
				let memberId = $('#memberId').val(); // 작성자 데이터 
				let replyContent = $('#replyContent').val(); // 댓글 내용
				let obj = {
						'boardId' : boardId,
						'memberId' : memberId,
						'replyContent' : replyContent
				};
				console.log(obj);
				
				// $.ajax로 송수신 
				$.ajax({
					type : 'POST',
					url : 'replies/add',
					data : {'obj' : JSON.stringify(obj)}, //JSON으로 변환
					success : function(result) {
						console.log(result);
						if(result == 1){
							alert('댓글 입력 성공!');
							getAllReplies();
						}
					}
				});//end ajax
			});// end btnAdd.click()

 

 

getAllReplies() //게시글 댓글 전체 가져오기 

 

// 게시글 댓글 전체 가져오기 
function getAllReplies() {
// 댓글을 가져오기 위해 boardId 필요
	let boardId = $('#boardId').val();
				
// url에 boardId 전송
	let url = 'replies/all?boardId=' + boardId;
				
// 가져올 데이터가 JSON이므로
// getJSON으로 파싱하는게 편함
	$.getJSON(
		url,
		function(data){
	// data : 서버에서 전송받은 list 데이터가 저장되어 있음,
	// getJSON() 에서 json데이터는
	// javascript object로 자동 parsing 됨
		console.log(data); // data의 타입 = obj
						
		let list = ''; // 댓글 데이터를 HTML에 표현할 문자열 변수 
						
	// $(컬렉션).each() : 컬렉션 데이터를 반복문으로 꺼내는 함수 
		$(data).each(function(){
	// this : 컬렉션의 각 인덱스 데이터를 의미
		console.log(this); 
	// 데이터 화면 출력 코드 
							
	// string을 date 타입으로 변경
			var replyDateCreated = new Date(this.replyDateCreated); // Data Date Data Date...
							
				list += '<div class="reply_item">'
					+ '<pre>'
					+ '<input type="hidden" id="replyId" value="'+ this.replyId +'">'
					+ this.memberId
					+ '&nbsp;&nbsp;' // 공백
					+ '<input type="text" id="replyContent" value="'+ this.replyContent +'">'
					+ '&nbsp;&nbsp;' // 공백
					+ replyDateCreated
					+ '&nbsp;&nbsp;' // 공백
					+ '<button class="btn_update">수정</button>'
					+ '<button class="btn_delete">삭제</button>'
					+ '</pre>'
					+ '</div>';
						
			});//end each()
						
					$('#replies').html(list);
			}
		); //end getJSON
	}//end getAllReplies()

 


replyAdd
// ajax 통신으로 댓글 JSON 데이터를 전송받아,
// DB에 저장하고, 저장에 성공하면 success 메세지를 다시 돌려줌

// ajax 통신으로 댓글 JSON 데이터를 전송받아,
    // DB에 저장하고, 저장에 성공하면 success 메세지를 다시 돌려줌
	private void replyAdd(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException{
		String obj = request.getParameter("obj");
		System.out.println(obj);
		
		JSONParser parser = new JSONParser();
		
		try {
			JSONObject jsonObject = (JSONObject)parser.parse(obj);
			
			int boardId = Integer.parseInt((String)jsonObject.get("boardId"));
			String memberId = (String) jsonObject.get("memberId");
			String replyContent = (String) jsonObject.get("replyContent");
			
			ReplyVO vo = new ReplyVO(0, boardId, memberId, replyContent, null);
			System.out.println(vo);
			
			int result = dao.insert(vo);
			if(result == 1) {
				response.getWriter().append("success");
			}
		} catch (ParseException e) {
			
			e.printStackTrace();
		} 
		
		
	}



replyList
// 게시글 번호를 바탕으로 DB에서 댓글 리스트 조회
// 조회된 댓글 리스트를 JSON 형태로 변경하여 클라이언트에 전송

 

// 게시글 번호를 바탕으로 DB에서 댓글 리스트 조회
    // 조회된 댓글 리스트를 JSON 형태로 변경하여 클라이언트에 전송
    private void replyList(HttpServletRequest request, HttpServletResponse response) 
    		throws ServletException, IOException{ // 예외 처리
    	System.out.println("replyList()");
		int boardId = Integer.parseInt(request.getParameter("boardId"));
		List<ReplyVO> list = dao.select(boardId);
		
		JSONArray jsonArray = new JSONArray();
		for(int i=0; i<list.size();i++) {
			JSONObject jsonObject = new JSONObject();
			ReplyVO vo = list.get(i);
			jsonObject.put("replyId", vo.getReplyId());
			jsonObject.put("boardId", vo.getBoardId());
			jsonObject.put("memberId", vo.getMemberId());
			jsonObject.put("replyContent", vo.getReplyContent());
			jsonObject.put("replyDateCreated", vo.getReplyDateCreated().toString()); // toString 꼭 넣기..
			jsonArray.add(jsonObject);
		}
		System.out.println(jsonArray.toString());
		response.getWriter().append(jsonArray.toJSONString());
		// toString or toJSONString 둘 다 가능
	}

 

 


detail.jsp 댓글 수정

// 수정 버튼을 클릭하면 선택된 댓글 수정
			$('#replies').on('click', '.reply_item .btn_update', function(){
				console.log(this);
				
				// 선택된 댓글의 replyId, replyContent 값을 저장 
				// prevAll() : 선택된 노드 이전에 있는 모든 형제 노드를 접근 
				var replyId = $(this).prevAll('#replyId').val();
				var replyContent = $(this).prevAll('#replyContent').val();
				console.log("선택된 댓글 번호 : " + replyId + ", 댓글 내용 : " + replyContent);
				
				//ajax로 데이터 전송하여
				//댓글 수정 기능 수행하고
				//수행 결과를 리턴하는 코드
				//ajax 요청 
				$.ajax({
					type : 'POST',
					url : 'replies/update',
					data: {
						'replyId' : replyId,
						'replyContent' : replyContent
					},
					success : function(result) {
						console.log(result);
						if(result == 'success'){
							alert('댓글 수정 성공!');
							getAllReplies();
						}
					
					}
				}); // end ajax()
			});// end replies.on()

 



replyController - replyUpdate()

// 전송된 데이터를 DB에 전달하여 댓글 수정
    // 수정 후 성공 메세지를 클라이언트로 전송
    private void replyUpdate(HttpServletRequest request, HttpServletResponse response)
    		throws ServletException, IOException { // 예외 처리
		int replyId = Integer.parseInt(request.getParameter("replyId"));
		String replyContent = request.getParameter("replyContent");
		ReplyVO vo = new ReplyVO(replyId, 0, "", replyContent, null);
		
		int result = dao.update(vo);
		if(result == 1) {
			response.getWriter().append("success");
		}
	}

 

 



detail.jsp 댓글 삭제 

$('#replies').on('click', '.reply_item .btn_delete', function(){
				console.log(this);
				
				// 선택된 댓글의 replyId, replyContent 값을 저장 
				// prevAll() : 선택된 노드 이전에 있는 모든 형제 노드를 접근 
				var replyId = $(this).prevAll('#replyId').val();
				
				console.log("선택된 댓글 번호 : " + replyId );
				
				//ajax로 데이터 전송하여
				//댓글 삭제 기능 수행하고
				//수행 결과를 리턴하는 코드
				//ajax 요청 
				$.ajax({
					type : 'POST',
					url : 'replies/delete',
					data: {
						'replyId' : replyId,
						
					},
					success : function(result) {
						console.log(result);
						if(result == 'success'){
							alert('댓글 삭제 성공!');
							getAllReplies();
						}
					}
				}); // end ajax()
			});// end replies

 



replyController - replyDelete()

 

private void replyDelete(HttpServletRequest request, HttpServletResponse response) 
    		throws ServletException, IOException {
		System.out.println("replyDelete()");
		int replyId = Integer.parseInt(request.getParameter("replyId"));
		
		int result = dao.delete(replyId);
		if(result == 1) {
			response.getWriter().append("success");
		}
    	
	}

 

 

 

 


 

 

replyAdd

 

등록 완료

 

replyUpdate

 

replyDelete

 

 

전체 코드 

 

https://github.com/hoongji/MVC_first

 

 


 

MVC 구조 그리기

 

더보기

list() : 

index.jsp -> BoardController -> dao.select() -> DB(pk - BoardId) -> List<BoardVO> list -> list.jsp

registerGET() : 

서블렛(registerGET)  -> register.jsp 

registerPOST() : 

register.jsp ->   BoardController -> dao.insert(vo) -> DB(vo) -> index.jsp

detail() : 

list.jsp -> BoardController -> dao.select(boardId) ->  DB(boardId) -> detail.jsp

updateGET() :

detail.jsp ->  BoardController -> dao.select(boardId) -> DB(boardId) -> update.jsp

updatePOST() :

update.jsp -> BoardController -> BoardVO -> DB(vo) -> detail.jsp

 

deletePOST() :

detail.jsp -> BoardController -> dao.delete(boardId) -> DB(boardId) -> index.jsp

 

 

 

댓글 MVC 구조

 

더보기

추가 

( ReplyController
ReplyVO
ReplyDAO
ReplyDAOImple
ReplyTable) 

replyAdd() :

detail.jsp -(getAllReplies)-> DB(모든 댓글 정보) ->jsp 응답
jsp -(추가 button)->서버(replies/add) -> dao.insert(vo) -> DB(vo) -> jsp("success")/getAllReplies

update:

jsp -(수정 button)->  서버(replies/update) -> DB (replyId,replyContent) -> 서버("success") ->jsp(alert/getAllReplies)

delete:

jsp -(삭제button)-> 서버(replies/delete) ->DB(replyId) ->서버("success") ->jsp(alert/getAllreplies)


* 클라이언트에서 삭제 버튼을 클릭하면 JavaScript가 실행

JavaScript 코드는 AJAX 요청을 생성하여 서버에 삭제할 댓글의 Id를 전송

서버는 해당 요청을 받고, 받은 데이터를 처리하기 위해 'replies/delete' 서블릿을 호출

서블릿은 받은 데이터를 처리하고, 데이터베이스에서 해당 댓글을 삭제한다

DB 에서 삭제가 완료되면 서버는 클라이언트에게 "success" 응답을 보냄

클라이언트는 AJAX 요청의 응답을 받아, 댓글 삭제가 성공했음을 확인하고 alert 메세지를 표시하고

getAllReplies() 함수를 호출해 삭제된 댓글을 제외한 나머지 댓글 목록을 다시 가져온다

 

 

 

 

 

페이징 처리 MVC

 

 

더보기

 

list.jsp -> 서버(list()) -> dao.select() ->  list.jsp(list) -> dao.getTotalCount() -> list.jsp(pageMaker)

 

* 1. 사용자가 페이지를 요청하면 클라이언트(list.jsp)가 서버(list.do)에 요청 보냄

2. 서버는 요청을 받고, 요청된 페이지의 게시글 목록(DB 쿼리)과 페이지 메이커 정보를 가져온다( list() )

3. 서버는 페이지 정보를 DAO에 전달하여 해당 페이지의 게시글 목록을 가져온다(DB)

4. DAO는 DB에서 게시글 목록을 가져와 서버에 반환한다. 

5. 서버는 게시글 목록과 전체 게시글 수를 클라이언트에게 보내준다.

6. 클라이언트는 받은 데이터를 화면에 출력해 사용자에게 보여준다. 

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함