2023.07.19 TIL

2023. 7. 19. 19:06TIL(Today I Learned)

(1) Spring ajax 사용법

- 코드 예시(프론트단)

<script type="text/javascript">
   		//날씨 정보를 받아오기(Ajax)
   		$.ajax({
   			url : "${root}/api/weather",
   			method : "GET",
   			data : {},
   			dataType : "json",
   			success : function(x){
   				alert("good");
   				console.log(x);
   				
   				//받아온 정보로 table 채우기
   				const tbody = document.querySelector("tbody");
   				tbody.innerHTML = "<tr>"
   									+	"<td>"+ x.response.body.items.item[0].baseDate +"</td>"	
   									+	"<td>"+ x.response.body.items.item[0].baseDate +"</td>"	
   									+	"<td></td>"	
   									+	"<td></td>"	
   									+	"<td></td>"	
   									+	"</tr>";
   			},
   			error : function(x){
   				alert("bad");
   				console.log(x);
   			},
   		});
   		
   		//받아온 정보로 table 채우기
   </script>

 

- 코드 예시(백), api 사용

package com.kh.app.api.weather;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
@RequestMapping("api/weather")
public class WeatherController {
	@GetMapping
	public List getWeather() throws Exception {
		//날씨 정보를 얻기
		StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtNcst"); /*URL*/
        urlBuilder.append("?" + URLEncoder.encode("serviceKey","UTF-8") + "=21CK6Reu1WPVAVGjpuz7jAoAAA8Wxwqmg25C5N4yFdcwsvraT3XgHwZnbFTIRcnZTC45BFzoISOQuUYYY%2BmcGg%3D%3D"); /*Service Key*/
        urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8") + "=" + URLEncoder.encode("1", "UTF-8")); /*페이지번호*/
        urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8") + "=" + URLEncoder.encode("1000", "UTF-8")); /*한 페이지 결과 수*/
        urlBuilder.append("&" + URLEncoder.encode("dataType","UTF-8") + "=" + URLEncoder.encode("JSON", "UTF-8")); /*요청자료형식(XML/JSON) Default: XML*/
        urlBuilder.append("&" + URLEncoder.encode("base_date","UTF-8") + "=" + URLEncoder.encode("20230718", "UTF-8")); /*‘21년 6월 28일 발표*/
        urlBuilder.append("&" + URLEncoder.encode("base_time","UTF-8") + "=" + URLEncoder.encode("0600", "UTF-8")); /*06시 발표(정시단위) */
        urlBuilder.append("&" + URLEncoder.encode("nx","UTF-8") + "=" + URLEncoder.encode("55", "UTF-8")); /*예보지점의 X 좌표값*/
        urlBuilder.append("&" + URLEncoder.encode("ny","UTF-8") + "=" + URLEncoder.encode("127", "UTF-8")); /*예보지점의 Y 좌표값*/
        URL url = new URL(urlBuilder.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-type", "application/json");
       
        BufferedReader rd;
        if(conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        } else {
            rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        }
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        
        rd.close();
        conn.disconnect();
		
        
        //데이터 정제
        String jsonStr = sb.toString();
        
        Gson gson = new Gson();
        
        Map jsonMap = gson.fromJson(jsonStr, Map.class);
        
        Map response = (Map)jsonMap.get("response");
        
        Map body = (Map)response.get("body");
        
        Map items = (Map)body.get("items");
        
        List itemList = (List)items.get("item");
        
        
        log.info(itemList.toString());
		
		return itemList;
	}
}

'TIL(Today I Learned)' 카테고리의 다른 글

2023.07.27 TIL  (0) 2023.07.27
2023.07.26. TIL  (0) 2023.07.26
2023.07.18 TIL  (0) 2023.07.18
2023.07.17 TIL  (0) 2023.07.17
2023.07.14 TIL  (0) 2023.07.14