Server

AJAX STEP 2 - Push Server

IT의 큰손 2023. 5. 15. 17:43
728x90

★ 데이터 전송 

  • 실시간으로 데이터를 갱신 하는 페이지
  • 필요 파일들 
> "Ex03.java"
> "Ex03Data.java" //**중요 
> "ex03.jsp" 
> "ex03data.jsp"
  • iframe
    • 현재 브라우저에서 새로운 브라우저를 띄우는 방법

실행 결과

 

■ Ex03.java : 디자인 담당

package com.test.ajax;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ex03.do")
public class Ex03 extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		//Ex03.java

		RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/ex03.jsp");
		dispatcher.forward(req, resp);
	}

}

 

■ Ex03Data.java : 데이터 담당

package com.test.ajax;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ex03data.do")
public class Ex03Data extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		AjaxDAO dao = new AjaxDAO();
		
		ResearchDTO dto = dao.getResearch(1);
		
		req.setAttribute("dto", dto);

		RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/ex03data.jsp");
		dispatcher.forward(req, resp);
	}

}

 

■ ex03.jsp : 디자인 담당

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
	#chart {
	
	}
	
	#chart > div {
		border : 1px solid #999;
		font-size : 12px;
		padding : 4px;
		text-align : right;
		margin-bottom : 5px;
	}
	
	#chart > div:nth-child(1) {
		
		background-color : tomato;
		color : white;
	}
	
	#chart > div:nth-child(2) {
		
		background-color : gold;
		color : white;
	}
	
	#chart > div:nth-child(3) {
		
		background-color : cornflowerblue;
		color : white;
	}
	
	#chart > div:nth-child(4) {
		
		background-color : orange;
		color : white;
	}

</style>
</head>
<body>

	<h1 id="title">설문 조사</h1>
	
	<div>주제 : <span id="question"></span></div>

	<div id="chart">
		
		<div><span class="item"></span>(<span class="cnt"></span>)</div>
		<div><span class="item"></span>(<span class="cnt"></span>)</div>
		<div><span class="item"></span>(<span class="cnt"></span>)</div>
		<div><span class="item"></span>(<span class="cnt"></span>)</div>

	</div>
	
	<hr>
	메모 : <input type="text">
	<hr>
	<iframe src="/ajax/ex03data.do" width="0" height="0" style="display:none;"></iframe>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>



</script>
</body>
</html>

 

■ ex03data.jsp : 데이터 담당

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>

</style>
</head>
<body>
	
	<input type="text">



<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>

	//안쪽 문서 > 바깥쪽 문서
// 	top.document.getElementById('title').textContent = 'test';
	
	top.document.getElementById('question').textContent = '${dto.question}';

	<c:forEach var="i" begin="0" end="3">
	top.document.getElementsByClassName('item')[${i}].textContent = '${dto.item[i]}';	
	top.document.getElementsByClassName('cnt')[${i}].textContent = '${dto.cnt[i]}';	
	top.document.querySelectorAll('#chart > div')[${i}].style.width = '${dto.cnt[i] * 40}px';
	</c:forEach>
	
	setTimeout(function() {
		
		location.reload();
		
	}, 5000);
	
</script>
</body>
</html>

 

★ 실행 결과

 

 

★ 실제 AJAX 구현

  • 1. 순수 자바스크립트(원래 Ajax)
  • 2. jQuery Ajax (가장 많이 사용)
  • 3. ES6 > Promise, await

■ 1. 순수 자바스크립트 사용

  • 필요 파일들
"Ex04.java"
"ex04.jsp"

 

■ Ex04.java

package com.test.ajax;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ex04.do")
public class Ex04 extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		//Ex04.java

		RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/ex04.jsp");
		dispatcher.forward(req, resp);
	}

}

■ ex04.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>

</style>
</head>
<body>
	<!-- ex04.jsp -->
	
	<h1>Ajax</h1>
	
	<div>
		<input type="text" id="txt1" class="short">
		<input type="button" value="버튼" id="btn1">
		<div id="div1"></div>
	</div>
	
	<hr>
	
	<div>
		다른 작업 : <input type="text">	
	</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>

	/* 
	
		Ajax 구현
		1. 순수 자바스크립트(원래 Ajax)
		2. jQuery Ajax
		3. ES6 > Promise, await
		
	*/
	
	const txt1 = document.getElementById('txt1');
	const btn1 = document.getElementById('btn1');
	const div1 = document.getElementById('div1');
	
	btn1.addEventListener('click', function() {
		
		//요청 > 서버로부터 데이터를 받아오기
		
		//Ajax 요청 > ajax 객체 > 서버와 통신하는 도구(전화기 > 편지)
		const ajax = new XMLHttpRequest();
		
		//readyState
		ajax.onreadystatechange = function() {
			
			console.log('readyState', ajax.readyState);
			console.log('status', ajax.status);
			console.log('  ');
			
		};
		
		//<form method='GET' action='페이지'>
		ajax.open('GET', '/ajax/ex04.txt'); //호출(x), 설정(o)
		
		ajax.send(); //실제 연결(= 호출) > == 전송 버튼(submit)을 누른 효과
		
		
	});

</script>
</body>
</html>

 

■ 실행 결과

  • readyState
1. UNSENT (숫자 0) : XMLHttpRequest 객체가 생성됨.

2. OPENED (숫자 1) : open() 메소드가 성공적으로 실행됨.

3. HEADERS_RECEIVED (숫자 2) : 모든 요청에 대한 응답이 도착함.

4. LOADING (숫자 3) : 요청한 데이터를 처리 중임.

5. DONE (숫자 4) : 요청한 데이터의 처리가 완료되어 응답할 준비가 완료됨.
  • status
 - 200 : 서버에 문서가 존재함.

 - 404 : 서버에 문서가 존재하지 않음.

 

실행 결과

 

728x90