💎 index.jsp
<h1>실시간 지진해일 긴급 대피장소</h1>
<button id="btn2">실시간 지진해일 긴급 대피장소 정보</button>
<br><br>
<table border="1" id="result2">
<thead>
<tr>
<th>시도명</th>
<th>시군구명</th>
<th>대피지구명</th>
<th>대피장소명</th>
<th>주소</th>
<th>경도</th>
<th>위도</th>
<th>수용가능인원수</th>
<th>대피소 분류명</th>
</tr>
</thead>
<tbody></tbody>
</table>
💎 Script
📢 ajax를 통한 비동기방식 XML 방식
- 전에 했던 API랑은 다르게 이번 API는 넘겨줄 데이터가 없기때문에 처리할 요청주소만 Spring으로 보내준다
$(function(){
$("#btn2").click(function(){
// 응답 데이터를 xml 형식으로 받을 때
$.ajax({
url : "shelter",
success : function(result){
const itemArr = $(result).find("row");
let value;
itemArr.each(function(index, item){
value += "<tr>"
+"<td>"+ $(item).find("sido_name").text() +"</td>"
+"<td>"+ $(item).find("sigungu_name").text() +"</td>"
+"<td>"+ $(item).find("remarks").text() +"</td>"
+"<td>"+ $(item).find("shel_nm").text() +"</td>"
+"<td>"+ $(item).find("address").text() +"</td>"
+"<td>"+ $(item).find("lon").text() +"</td>"
+"<td>"+ $(item).find("lat").text() +"</td>"
+"<td>"+ $(item).find("shel_av").text() +"</td>"
+"<td>"+ $(item).find("shel_div_type").text() +"</td>"
+"</tr>"
})
$("#result2 > tbody").html(value);
},
error : function(){
console.log("통신 실패");
}
})
})
})
💎 Spring
📢 OpenAPIController
// xml 형식으로 지진해일 대피소 OpenApi 활용하기
@RequestMapping(value="shelter",produces = "text/xml; charset=UTF-8")
@ResponseBody
public String shelterList() throws IOException{
// OpenAPI 서버로 요청하고자 하는 url 작성
String url = "http://apis.data.go.kr/1741000/TsunamiShelter3/getTsunamiShelter1List";
url +="?serviceKey=" + SERVICEKEY;
url +="&pageNo=1";
url +="&numOfRows=20"; // 결과 개수
url +="&returnType=xml";
// 1. 작성된 url 정보를 넣어 URL 객체 생성
URL requestUrl = new URL(url);
System.out.println(url);
// 2. 생성된 URL 객체로 URLConnection 생성
HttpURLConnection urlConn = (HttpURLConnection) requestUrl.openConnection();
// 3. 요청 시 필요한 Header 설정
urlConn.setRequestMethod("GET");
// 4. 해당 OpenAPI 서버로 요청 후 입력스트림을 통해서 응답데이터 읽어오기
BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String responseText = "";
String line;
while((line = br.readLine()) != null){
responseText += line;
}
// 5. 다 사용한 스트링 반납 및 연결 해제
br.close();
urlConn.disconnect();
System.out.println(responseText);
return responseText;
}