FISA 3기

비동기 처리 기술 학습

ayleeee 2024. 8. 7. 15:48
function loadDoc() {
  const xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt");
  xhttp.send();
}

https://www.w3schools.com/js/js_ajax_http.asp
  • XMLHttpRequest 
    • 서버와 상호작용할 때 사용
    • XHR을 사용하면 페이지의 새로고침 없이도 URL에서 데이터를 가져올 수 있음
  •  xhttp.onreadystatechange 
    • readystate 속성이 변경될 때 호출할 함수 정의
    • readystate
      • 0 : request not initialized
      • 1 : server connection established
      • 2 : request received
      • 3 : processing request
      • 4 : request finished and response is ready 
  • xttp.open 
    • 새롭게 만들어진 request를 초기화 하거나, 존재하던 XMLHttpRequest를 재초기화
    • open(method, url)
  • xttp.send
    • sends the request to the server 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>비동기 처리 기술 학습</h3>
	<br>
	<button id="btnView3">json data 활용</button>
	<script>
	
		btnView3.addEventListener("click",function(){
			const xhttp = new XMLHttpRequest();
			xhttp.onreadystatechange = function() {
				if (this.readyState == 4 && this.status == 200) {
					let resData = this.responseText;
					console.log(resData, typeof(resData)); 
					console.log(resData.name, typeof(resData));
					
					console.log("가공 직후")
--
					resData = JSON.parse(resData); 
					console.log(resData.name, typeof(resData));
				}
			};
			xhttp.open("GET", "jsonRes.jsp"); 
			xhttp.send(); 
		});
	</script>
</body>
</html>
  • jsonRes.jsp 파일의 내용을 읽어서 가공하기
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
{"name":"이름", "message":"건강에너지","age":10}
  • json 형식 내용 파싱하는 법 : JSON.parse()

package step04.ajax;

import java.io.IOException;
import java.io.PrintWriter;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class FisaServlet extends HttpServlet {
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
        // PrintWriter : 서블릿에서 응답을 작성할 때 자주 사용 
		PrintWriter out = response.getWriter();
		out.println("<img src='../images/images.jfif'>");
	}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>비동기 처리 기술 학습</h3>
	<br>
	<div id="imgView"></div>
	<button id="btnView">이미지 보이기</button>
	<button id="btnView2">이미지 숨기기</button>
	<hr>
    <script>
		btnView.addEventListener("click",function(){
			reqRes();
		});
		
		btnView2.addEventListener("click",function(){
			imgView.innerHTML = null;
		});
		
		function reqRes() {
			// 비동기 기반의 요청, 응답 처리 기술
			const xhttp = new XMLHttpRequest();
			// 응답시 자동 실행되는 로직 등록 : 콜백함수 등록 
			/* 서버와 클라이언트가 소통(요청과 응답)진행시점에 자동 호출
			this.readyState 값이 변경시 마다 감시(on)를 해서 자동 호출되게 해주는 속성
			 */
			xhttp.onreadystatechange = function() {
				// 응답완료 : 4 / 정상응답 :200인 경우만 실행되는 블록의 조건식
				if (this.readyState == 4 && this.status == 200) {
					imgView.innerHTML = this.responseText
					//alert(this.reponseText);
					
				}
			};
			xhttp.open("GET", "../ajaxfisa"); // get방식으로 ajaxfisa 서블릿에게 요청 설정
			//xhttp.open("GET", "ajaxfisa.jsp");
			xhttp.send(); // 실제 서버에 요청 수행
		}
	</script>
</body>
</html>
  • Servlet (서블릿)
    • 자바 프로그래밍 언어를 사용하여 웹 서버에서 동적으로 콘텐츠를 생성하기 위한 서버 측 프로그램 
    • HTTP 요청 처리, 그에 따른 응답 생성. 비즈니스 로직이나 데이터 처리, 요청 파라미터 분석, 데이터베이스와 상호작용 수행 
    • service() : 클라이언트 요청을 처리할 때마다 호출 
    • 서버 로직 
  • JSP (JavaServer Pages)
    • JSP는 HTML 내 자바 코드 삽입, 동적으로 웹 페이지를 생성하는 서버 측 기술
    • JSP는 최초 요청 시 서블릿으로 변환, 이후에는 서블릿으로 동작
    • 사용자 인터페이스 
(1) ../ajaxfisa 에 대한 url 요청이 'FisaServlet'에 의해 처리됨
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();
    out.println("<img src='../images/images.jfif'>");
}

(2) 이 서블릿이 ../ajaxfisa URL로 요청을 받으면, 
다음과 같은 HTML 응답을 생성하여 클라이언트에게 반환
<img src='../images/images.jfif'>

(3) if (this.readyState == 4 && this.status == 200) {
    imgView.innerHTML = this.responseText;
}

위의 HTML 응답은 자바스크립트 코드에서 this.responseText로 받아짐