본문 바로가기
Spring/Legacy

AJAX & JSON

by pms93 2022. 10. 26.

< jsp_AJAX >

<%@ 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>
		var xmlReq;
		
		function send() {
			<%--
				XMLHttpRequest
				 - ajax(비동기통신)통신을 하기 위한 class
				 
				 .onreadystatechange
				  - 비동기 통신을 통한 clientserver간의 교신을 할 경우 5가지의 readystate code가 존재한다.
				  {
				   	1. UNSENT (숫자 0) : XMLHttpRequest 객체가 생성됨.
 					2. OPENED (숫자 1) : open() method가 성공적으로 실행됨.
 					3. HEADERS_RECEIVED (숫자 2) : 모든 요청에 대한 응답이 도착함.
					4. LOADING (숫자 3) : 요청한 데이터를 처리 중임.
 					5. DONE (숫자 4) : 요청한 데이터의 처리가 완료되어 응답할 준비가 완료됨.
 				  }
				  - 요청의 상태가 각 code에 해당하는 경우마다 아래에서 명시한 changeText method가 호출된다.(정상적인 교류시에 총 5번의 호출)
				  
				  .open
				   - client의 data 전송방식과 server로 보낼 요청url을 설정한다.
				  
				  .send
				   - server로 보내질 데이터를 명시한다.
			--%>
			xmlReq = new XMLHttpRequest();
			xmlReq.onreadystatechange = changeText;
			xmlReq.open("POST", "/");
			xmlReq.send(document.getElementById("req").value);
		}
		
		function changeText() {
			if (xmlReq.readyState == 4 && xmlReq.status == 200) { <%-- status : 흔히 아는 200, 302, 404, 500 등의 코드 --%>
				<%-- 
					.responseText
					 - server가 client에게 응답한 data를 문자열로 넘겨받는다.
				--%>
				document.getElementById("print").innerHTML = xmlReq.responseText;
			}
		}
	</script>
</head>
<body>
	<h3> !! AJAX Practice !! </h3>
	<div id = "print">출력데이터</div> <br>
	<input type = "text" id = "req"> <br>
	<button onclick = "send()">서버 응답값 보기</button>
</body>
</html>

 

< jsp_JSON >

<%@ 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>
		var xmlReq;
		
		function search() {
			xmlReq = new XMLHttpRequest();
			xmlReq.onreadystatechange = displaySearchResult;
			xmlReq.open("POST", "search");
			xmlReq.send(document.getElementById("searchText").value);
		}
		
		function displaySearchResult() {
			var content = ""; 
			var returnData;
			if (xmlReq.readyState == 4 && xmlReq.status == 200) {
				<%-- 
					Java에서 return한 data가 json일 경우 jsp에서 또한 이 데이터를 사용할 시에 JSON으로 형변환해야 한다.
					* 위 작업을 하기 위해서 jackson-databind Library 필요
					  (jackson databind란? java의 객체를 JSON으로 형변환이 가능하게끔 해주는 Library)
				--%>
				returnData = JSON.parse(xmlReq.responseText);
				
				for (var cnt = 0; cnt <= returnData.songs.length; cnt++) {
					<%-- tbody에 innerText method를 통해 row와 data 삽입이 가능하다. --%>
					content +=
						"<tr>" + 
							"<td>" + returnData.songs[cnt].title + "</td>" + 
							"<td>" + returnData.songs[cnt].artist + "</td>" + 
							"<td>" + returnData.songs[cnt].price + "</td>" + 
						"</tr>"
				}
				
				document.getElementById("content").innerHTML = content;
			}
		}
	</script>

</head>
<body>
	<h3> !! AJAX !! </h3>
	<input type = "text" id = "searchText" placeholder = "검색어 입력" onkeyup = "search()">
	
	<table>
		<thead>
			<tr>
				<th>Title</th>
				<th>Artist</th>
				<th>Price</th>
			</tr>
		</thead>
		
		<tbody id = content></tbody>
	</table>
</body>
</html>

 

< java >

package com.ms.blog.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ms.blog.service.BlogService;

@Controller
public class BlogController {

	// AJAX
	@ResponseBody
	@RequestMapping("/")
	public String home(@RequestBody(required = false) String request) {
		
		// @ResponseBody
		//  - controller method에 responseBody annotation을 적용시키는 순간 return값은 viewResolver에게 전달되는것이 아닌 서버의 응답값을 jsp에 return한다.
		
		// @RequestBody
		//  - jsp에서 client가 server로 요청한 데이터를 전달받을 수 있다.
		//  - jsp의 tag name or id와 controller method의 매개변수명이 동일할 필요는 없다.
		return "client가 server에게 전달한 데이터 : " + request + "\n서버의 응답값 전달"; 
	}
	
	
	// AJAX with JSON
	@GetMapping("json")
	public String json() { return "json"; }
	
	
	@ResponseBody
	@PostMapping(value = "search", produces = "application/json; charset = UTF-8") // JSON으로 데이터를 주고받기 위해선 application/json설정이 되어야 한다.
	public String json(@RequestBody(required = false)String searchText) {
		// JSON데이터의 기본적인 형태는 HashMap과 일치한다. (Key를 통한 Value산출이 가능)
		/* 
		 ex) JSON Data Format
		 {
		 	"Key_1" : [
		 	{ "Key" : "Values", "Key" : "Values" },
		 	{ "Key" : "Values", "Key" : "Values" },
		 	{ "Key" : "Values", "Key" : "Values" },
		 	{ "Key" : "Values", "Key" : "Values" }
		 ]}
		  - Key_1이라는 배열 내에 Hash맵들의 참조값이 들어가는 격
		  - Key_1.key연산을 통해 해당 key값의 value산출이 가능하다.(jsp에서도 가능)
		*/ 
		return null;
	}
}

'Spring > Legacy' 카테고리의 다른 글

DAO(Repository) & Mapper.xml  (0) 2022.10.25
Spring <-> DB Connection  (0) 2022.10.25
Controller in Legacy Package  (0) 2022.10.18