WEB JAVA SPRING/JS

Ajax 개념과 코드 적용(댓글 등록)

sshhhh 2023. 9. 12.

<<<Ajax를 이용한다면>>>

웹 페이지 전체를 다시 로딩하지 않고 일부분만을 갱신할 수 있다. 

즉 백그라운드 영역에서 서버와 통신하여, 그 결과를 웹 페이지의 일부분에만 표시할 수 있다.\

 

댓글 등록시 바로 등록되고 삭제시 바로 삭제된다. (새로고침되지않음)

세션 등록을 했기 때문에 댓글 작성자만 삭제 가능하다.

 

 

 

Asynchronous JavaScript and XML 으로 동적인 웹 페이지를 만들기 위한 개발 기법이며

이때 서버와는 다음과 같은 다양한 형태의 데이터를 주고받을 수 있다.

 

 - JSON

 - XML

 - HTML

 - 텍스트 파일 등

 

 

동작원리

① : 사용자에 의한 요청 이벤트가 발생합니다.

② : 요청 이벤트가 발생하면 이벤트 핸들러에 의해 자바스크립트가 호출됩니다.

③ : 자바스크립트는 XMLHttpRequest 객체를 사용하여 서버로 요청을 보냅니다.

    이때 웹 브라우저는 요청을 보내고 나서, 서버의 응답을 기다릴 필요 없이 다른 작업을 처리할 수 있습니다.

④ : 서버는 전달받은 XMLHttpRequest 객체를 가지고 Ajax 요청을 처리합니다.

⑤와 ⑥ : 서버는 처리한 결과를 HTML, XML 또는 JSON 형태의 데이터로 웹 브라우저에 전달합니다.

    이때 전달되는 응답은 새로운 페이지를 전부 보내는 것이 아니라 필요한 데이터만을 전달합니다.

⑦ : 서버로부터 전달받은 데이터를 가지고 웹 페이지의 일부분만을 갱신하는 자바스크립트를 호출합니다.

⑧ : 결과적으로 웹 페이지의 일부분만이 다시 로딩되어 표시됩니다.

 

 

참조 : http://www.tcpschool.com/ajax/intro

 

 


간단한 예시 코드

 

 

exam01

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
	#msgView {
		border: 1px solid red;
		height: 200px;
		width: 500px;
	}
</style>
<script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
	$(document).ready(function() {
		
		$('button').click(function() {
			/*
				url		: 요청주소(문자열)
				type	: 요청메소드(문자열)
				data	: 요청파라미터(문자열, 객체)
				success	: 수신성공(함수)
				error	: 수신실패(함수)
			*/
			$.ajax({
				url: 'hello.jsp',
				success: function(data) {
					$('#msgView').append(data)
				}
			/*  id : div 안에서 출력하고 싶어서 값을 줌 
			         append로 계속 추가되면서...출력
			    - hello.jsp가 data(=파라미터)로 전달돼
			
			*/
			
			
			, error: function() {
					alert('실패')
				}
			})
			
		})
	})
</script>
</head>
<body>
	<h2>서버에서 받은 메세지</h2>
	<div id="msgView"></div>
	<button>서버에서 자료요청</button>
</body>
</html>

 

 

exam02

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> 입력값 표현 ~</title>
<script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
	$(document).ready(function() {
		
		$('button').click(function() {
			
			let name = $('#name').val() ////아이디 name인거 선택한 양식의 값을 가져와
			let age = $('#age').val()
			
			/*
			$.post('param.jsp', {'name': name, age: age}, function(data) {
				$('#debug').val(data)
			})
			*/
			
			/*			
			$.get('param.jsp', "name=hong&age=25", function(data) {
				$('#debug').val(data)
			})
			*/
			
			
		
			// param.jsp?name=hong&age=25
			$.ajax({
				type: "get",
				url : "param.jsp",
			//	data: 'name=hong&age=25',
			//	data: 'name=' + name + '&age=' + age,
				data: {
					name: name,
					age: age
				},
				success : function(data) {
					$('#debug').val(data.trim())
					//trim() :문자열공백제거
					
				}, error : function(error) {
					alert('오류상태코드 : ' + error.status)
				}
			})
			
			
			
			/* get,post(jquary)는 동시에 일을 못해서
			  그래서 ajax로 갔다 -> 다른일 가능
			*/
			
			
			
			
		})
		
	})
</script>
</head>
<body>
       <!-- 많이적고싶어서 블로그 내용물 같은거   -->
	<textarea rows="10" cols="80" id="debug"></textarea><br>
	
	이름 : <input type="text" name="name" id="name"><br>
	나이 : <input type="text" name="age" id="age"><br>
	<button>호출</button>
</body>
</html>

 

exam03

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
	$(document).ready(function() {
		
		$.ajax({
			url: 'person.jsp',
			datatype: 'json',
			success: function(data) {
				console.log(data)
				console.log(typeof data)
				memberList = eval(data)
/* memberList : 함수  저 person.json 가져와,


   eval : 문자열을 코드로 인식 */
//				memberList = JSON.parse(data)
				console.log(memberList)
			}
		})
	})
</script>
</head>
<body>
</body>
</html>
 

 

 

 


웹페이지 댓글 작성 코드

 

 

 

 

- html view

-script (ajax)

 

<<댓글 등록>>

<<댓글 삭제>>

 

 

 

전체코드

<%@page import="kr.co.mlec.board.vo.BoardVO"%>
<%@page import="kr.co.mlec.board.dao.BoardDAO"%>
<%@page import="kr.co.mlec.util.JDBCClose"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="kr.co.mlec.util.connectionFactory"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page import="java.sql.*"%>
<!DOCTYPE html>
<%--
	http://localhost:9999/Mission-Web/jsp/board/detail.jsp?no=3

	작업순서
	1. 요청 URL의 파라미터 분석 => 게시글 번호 추출?
	2. DB tbl_board에서 추출된 게시글번호의 게시물 조회
	3. HTML에 조회된 게시물을 연결 화면 구성
	
 --%>


<html>
<head>
<meta charset="UTF-8">
<title>게시판 상세 페이지</title>
<style type="text/css">
table.type02 {
	border-collapse: separate;
	border-spacing: 0;
	text-align: left;
	line-height: 1.5;
	border-top: 1px solid #ccc;
	border-left: 1px solid #ccc;
	margin: 20px 10px;
}

table.type02 th {
	width: 150px;
	padding: 10px;
	font-weight: bold;
	vertical-align: top;
	border-right: 1px solid #ccc;
	border-bottom: 1px solid #ccc;
	border-top: 1px solid #fff;
	border-left: 1px solid #fff;
	background: #eee;
	text-align: center;
}

table.type02 td {
	width: 700px;
	padding: 10px;
	vertical-align: top;
	border-right: 1px solid #ccc;
	border-bottom: 1px solid #ccc;
	text-align: center;
}

table.thContent {
	width: 3500px;
}

table.type3 {
	border-collapse: collapse;
	border-spacing: 0;
	text-align: center;
	line-height: 1.5;
	border-top: 1px solid #ccc;
	border-bottom: 1px solid #ccc;
	border-right: 1px solid #ccc;
	border-left: 1px solid #ccc;
	margin: 20px 10px;
}

table.type3 th {
	border-right: 1px solid #ccc;
	border-bottom: 1px solid #ccc;
	border-top: 1px solid #fff;
	border-left: 1px solid #fff;
	text-align: center;
}

table.type3 td {
	border-right: 1px solid #ccc;
	border-bottom: 1px solid #ccc;
	text-align: center;
}
</style>

<link rel="stylesheet" href="/Mission-Web/css/layout.css">
<link rel="stylesheet" href="/Mission-Web/css/board.css">
<script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
	function doAction(type) {

		switch (type) {
		case 'R':
			location.href = "${pageContext.request.contextPath}/board/replyForm.do?no=${param.no}"
			break;
		case 'U':
			location.href = "${pageContext.request.contextPath}/board/updateForm.do?comNo=${param.no}"
			break;
		case 'D': 
			location.href = "${pageContext.request.contextPath}/board/delete.do?no=${param.no}"
			break;
		case 'L':
			location.href = "${pageContext.request.contextPath}/board/list.do"
			break;

		case 'A':
			$.ajax({ 
				url : "${pageContext.request.contextPath}/board/like.do",
				cache : false,
				data : {
					'comNo': ${param.no}
				},
													// 파라미터 전송 형태(표준 쿼리형태)로 만들어줌
				success : function(data) { // ajax통신 성공시 넘어오는 데이터 통째 이름 =data
					alert(" 좋아요♥ "); // data중 put한 것의 이름 like
			//		$("#like_result").html(data.like); // id값이 like_result인 html을 찾아서
					location.reload();									// data.like값으로 바꿔준다.
					
				},
				error : function(request, status, error) {
					alert("좋아요 실패 다시 클릭하세요!")
				}
			});
					
		}

	}




//댓글등록
 
	$(document).ready(
					function() {
						$('#writeMention').click( //id=writeMention인 버튼이 클릭되면 실행된다.
										function() {	
											$.ajax({ //MentionWriteController로 이동
												'url' : "${ pageContext.request.contextPath }/mentionWrite.do",  // 클라이언트가 요청을 보낼 서버의 URL 주소
												type: 'post', //요청방식
												data : {
													 // 서버에서 보내줄 데이터의 타입
													//공유영역에 등록되어있는 것들
													commentNo : ${ board.comNo },
													mentionID: '${userVO.id}',
													mentionContent: $('#mentionContent').val()
												},
												success : function() { //성공시 reload
												
													window.location.reload()
												}				
											})
										})
					})
					 
					
//댓글삭제
	$(document).ready(
					function() {
						// class="deleteMention"인 버튼 클릭되면 실행
						$('.deleteMention').click(function(){
							
							var no = $(this).attr("data"); //data="${mention.mentionNo }
							//글번호, 댓글번호 다 가져온다.
							location.href="${pageContext.request.contextPath}/mentionDelete.do?mentionNo=" + no+"&comNo=${param.no}";
							
						});
					});
					
					
</script>
</head>
<body>
	<header>
		<jsp:include page="/jsp/include/topMenu.jsp" />
	</header>


	<!-- Body content -->
	<div class="page-head">
		<div class="container">
			<div class="row">
				<div class="page-head-content">
					<h1 class="page-title">리뷰이야기</h1>
				</div>
			</div>
		</div>
	</div>
	<!-- End page header -->



	<section>
		<div align="center">
			<hr>
			<h2>&emsp;&emsp;리뷰 상세 보기</h2>
			<hr>
			<br>
			<table class="type02">
				<tr>
					<th>번호</th>
					<td style="padding-left: 10px">${ board.comNo }</td>
				</tr>
				<tr>
					<th>작성자</th>
					<td style="padding-left: 10px">${ board.id }</td>
				</tr>
				<tr>
					<th>제목</th>
					<td style="padding-left: 10px">${ board.comTitle }</td>
				</tr>

				<tr>
					<th height="200px"><br>
					<br>
					<br>내용</th2>
					<td style="padding-left: 10px">${ board.comContent }</td>
				</tr>
				<tr>
					<th>조회수</th>
					<td style="padding-left: 10px">${ board.viewCnt + 1 }</td>
				</tr>
				<tr>
					<th>등록일</th>
					<td style="padding-left: 10px">${ board.regDate }</td>
				</tr>
				<tr>
					<th>첨부파일</th>
					<td style="padding-left: 10px"><c:forEach
							items="${ fileList }" var="file">
							<a
								href="${ pageContext.request.contextPath}/upload/${file.fileSaveName}">
								${ file.fileOriName } </a>
							(${ file.fileSize } bytes)<br>
						</c:forEach></td>
				</tr>
				<tr>
					<th width="100px" class="tg-ltmv" style="text-align: center;">좋아요
						수</th>
					<td width="500px" style="padding-left: 10px">${ board.comLikeCnt }</td>
				</tr>
			</table>

			<br>
			<button onclick="doAction('R')">답글</button>
			&emsp;
			<c:if test="${ board.id eq userVO.id }">
				<button onclick="doAction('U')">수정</button>
				&emsp;
			</c:if>
			<c:if test="${ board.id eq userVO.id || userVO.type == 'S'}">
				<button onclick="doAction('D')">삭제</button>
				&emsp;
			</c:if>
			<button onclick="doAction('L')">목록</button>
			&emsp;
			<c:if test="${ board.id ne userVO.id}">
				<button onclick="doAction('A')" id="like">좋아요</button>
			</c:if>

			<!-- 댓글  -->
			<hr>
			<h2>&nbsp;댓글</h2>
			<hr>



			<div class="container">
				<div id="mention">
					<table class="type3">
						<!-- 댓글 목록 -->
						<!-- 공유영역 등록-->
						<c:if test="${not empty requestScope.mentionList }">
							<c:forEach var="mention" items="${requestScope.mentionList}">

								<tr>
									<!-- 아이디, 작성날짜 -->
									<td>
										<div>
											${mention.mentionId}<br>${mention.regDate}
										</div>
									</td>
									<!-- 본문내용 -->
									<td>
										<div>${mention.mentionContent}</div>
									</td>

									<!-- 버튼 -->
									<td>
										<!-- 댓글 작성자만 수정, 삭제 가능하도록 --> 
										<c:if test="${mention.mentionId == sessionScope.userVO.id || userVO.type == 'S' }">
											<button class="deleteMention" data="${mention.mentionNo }">삭제</button>
										</c:if>

									</td>
								</tr>
							</c:forEach>
						</c:if>


						<!-- 로그인 했을 경우만 댓글 작성가능 -->
						<c:if test="${sessionScope.userVO !=null}">
							<tr bgcolor="#F5F5F5">


								<!-- 아이디 뜨는 부분 -->
								<td width="155px">
									<div>${sessionScope.userVO.id}</div>

								</td>
								<!-- 댓글 적는 부분-->
								<td width="550px">
									<div>
										<textarea name="mentionContent" id="mentionContent" rows="4"
											cols="70"></textarea>
									</div>
								</td>
								<!-- 댓글 등록 버튼 -->
								<td width="155px">
									<div id="btn" style="text-align: center;">
										<p>
											<button id="writeMention">댓글등록</button>
											<!-- type="submit" -->
										</p>
									</div>
								</td>

							</tr>
						</c:if>
					</table>
					<br>
				</div>
			</div>
		</div>





	</section>
	<footer>
		<%@ include file="/jsp/include/footer.jsp"%>
	</footer>
</body>
</html>

 

댓글