본문 바로가기

Spring boot

naver Open api로 가져온 Json 데이터를 ajax로 jsp view에 뿌리기

https://developers.naver.com/docs/common/openapiguide/appregister.md#%EC%95%A0%ED%94%8C%EB%A6%AC%EC%BC%80%EC%9D%B4%EC%85%98-%EB%93%B1%EB%A1%9D

 

 

사전 준비 사항 - Open API 가이드

사전 준비 사항 네이버 오픈API를 사용하려면 먼저 네이버 개발자 센터에서 애플리케이션을 등록하고 클라이언트 아이디와 클라이언트 시크릿을 발급받아야 합니다. 클라이언트 아이디와 클라

developers.naver.com

0. 일단 내 어플리케이션을 등록한다.

 

 

사전 준비 사항 - Open API 가이드

사전 준비 사항 네이버 오픈API를 사용하려면 먼저 네이버 개발자 센터에서 애플리케이션을 등록하고 클라이언트 아이디와 클라이언트 시크릿을 발급받아야 합니다. 클라이언트 아이디와 클라

developers.naver.com

 

1. contorller 

import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/naver")
public class naverController {


	@ResponseBody
	@GetMapping("/naverShopping")
	public String naverShopping() {

		String query = "원피스";
		ByteBuffer buffer = StandardCharsets.UTF_8.encode(query);
		String encode = StandardCharsets.UTF_8.decode(buffer).toString();

		URI uri = UriComponentsBuilder.fromUriString("https://openapi.naver.com").path("/v1/search/shop.json")
				.queryParam("query", encode).queryParam("display", 10).queryParam("start", 1).queryParam("sort", "sim")
				.encode().build().toUri();

		RestTemplate restTemplate = new RestTemplate();

		RequestEntity<Void> req = RequestEntity.get(uri).header("X-Naver-Client-Id", "클라이언트 아이디 입력")
				.header("X-Naver-Client-Secret", "시크릿 주소 입력").build();

		ResponseEntity<String> result = restTemplate.exchange(req, String.class);
		log.info(result.getBody());

	

		return result.getBody();
	}

}

2. js 

 


//jsp view가 보여지는 동시에 start라는 function이 실행된다. 
start();

function start() {
	$.ajax({
		url: "/admin/naver/naverShopping",
		type: 'get',
		dataType: 'json',
		success: function(data) {
			//데이터를 파싱한 후
			var jsonObject = JSON.stringify(data);
			var jData = JSON.parse(jsonObject);

			//resultHtml이라는 function을 실행시킨다. 
			resultHtml(jData);

		},

		error: function(xhr, textStatus) {

			console.log(xhr.responseText);

			console.log("에러");

			return;

		}

	});//ajax
}



function resultHtml(data) {




	var html = "";
	//데이터의 길이만큼 <div>가 계속 생성될 예정이다. 
	$.each(data, function(key, value) { //  { key:[{}] } 
		if (key == "items") {
			for (var i = 0; i < value.length; i++) {
				html += "<div class='card h-100'>";
				html += "<form id ='frm1'>";
				html += "<img class='card-img-top' src='" + value[i].image + "' alt='...' />";
				html += "<div class='card-body p-4'>";
				html += "<div class='text-center'>";
				html += "<h5 class='fw-bolder' id='title'>" + value[i].title + "</h5>";
				html += value[i].lprice + " 원<br>";
				html += "<input type ='hidden' name ='title' value ='" + value[i].title + "'>";
				html += "<input type ='hidden' name ='link' value ='" + value[i].link + "'>";
				html += "<input type ='hidden' name ='image' value ='" + value[i].image + "'>";
				html += "<input type ='hidden' name ='lprice' value ='" + value[i].lprice + "'>";
				html += "<input type ='hidden' name ='hprice' value ='" + value[i].hprice + "'>";
				html += "<input type ='hidden' name ='mallName' value ='" + value[i].mallName + "'>";
				html += "<input type ='hidden' name ='productId' value ='" + value[i].productId + "'>";
				html += "<input type ='hidden' name ='brand' value ='" + value[i].brand + "'>";
				html += "<input type ='hidden' name ='maker' value ='" + value[i].maker + "'>";
				html += "<input type ='hidden' name ='category1' value ='" + value[i].category1 + "'>";
				html += "<input type ='hidden' name ='category2' value ='" + value[i].category2 + "'>";
				html += "<input type ='hidden' name ='category3' value ='" + value[i].category3+ "'>";
				html += "<input type ='hidden' name ='category4' value ='" + value[i].category4 + "'>";
				html += "<input type ='hidden' name ='productType' value ='" + value[i].productType + "'>";
				html += "<a  href='javascript:;' onclick ='pop(this);'>누르기</a>";
				html += "</div>";
				html += "</div>";
				html += "<div class='card-footer p-4 pt-0 border-top-0 bg-transparent'>";
				html += "<div class='text-center'>";
				html += "<a class='btn btn-outline-dark mt-auto' href=''>View options</a>";
				html += "</div>";
				html += "</div>";
				html += "</form>"
				html += "</div>";

			}
		}
		//jsp 에 뿌려준다.
		$("#start").append(html);
	});




}

 

 

다음엔 json을 dto에 담아서 하는 방법도 해볼 예정이다.