JSP/연습

공공데이터 뽑기

SEOKIHOUSE 2023. 7. 14. 17:39

1)자바스크립트에서만

 

https://www.data.go.kr/tcs/dss/selectApiDataDetailView.do?publicDataPk=15062893 

<%@ 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>
	<style>
		img {
			width:300px;
		}
        .content {
        	width:900px;
        }
		table {
        	width:3000px;
        }
	</style>
</head>
<body>
	<button onclick="f()">버튼</button>
	<table border='1' id="table">
		
		
	</table>
	<script>
	function f() {
		var xhr = new XMLHttpRequest();
		var url = 'http://apis.data.go.kr/6480000/gyeongnamcultural/gyeongnamculturallist'; /*URL*/
		var queryParams = '?' + encodeURIComponent('serviceKey') + '='+'%2Bt74wBuvAszqEeE9BKcwwW4MceBu4icZ6TP2u6KGnnIjxm%2FxHVRAl1CKQb5OKgW932n5357ZBdP78FrQnHOwAQ%3D%3D'; /*Service Key*/
		queryParams += '&' + encodeURIComponent('pageNo') + '=' + encodeURIComponent('1'); /**/
		queryParams += '&' + encodeURIComponent('numOfRows') + '=' + encodeURIComponent('10'); /**/
		queryParams += '&' + encodeURIComponent('resultType') + '=' + encodeURIComponent('json'); /**/
		xhr.open('GET',url + queryParams);
		xhr.onreadystatechange = function () {
		    if (this.readyState == 4) {
		    	let datas =JSON.parse(this.responseText);
		    	console.log(datas.gyeongnamculturallist.body.items.item);
		    	
		    	let items = datas.gyeongnamculturallist.body.items.item;
		    	let tables =  document.querySelector('table');
		    	
		    	tables.innerHTML +=
    				'<tr>'+
						'<th>지정번호(세부)</th>'+
						'<th>명칭</th>'+
						'<th>명칭(한문)</th>'+
						'<th>문화재 설명</th>'+
						'<th>수량(면적)</th>'+
						'<th>소유자</th>'+
						'<th>관리자</th>'+
						'<th>시대구분</th>'+
						'<th>지정일</th>'+
						'<th>주소분류1</th>'+
						'<th>UTMKX좌표값</th>'+
						'<th>UTMKX좌표값</th>'+
						'<th>첨부파일1</th>'+
						'<th>첨부파일2</th>'+
						'<th>첨부파일3</th>'+
					'</tr>';
		    	
		    		for(let i =0; i<items.length; i++) {
		    			tables.innerHTML +=
		    				'<tr>'+
								'<td>'+items[i].DOJIJUNG_NO+'</td>'+
								'<td>'+items[i].MYONGCHING+'</td>'+
								'<td>'+items[i].MYONGCHING_HANMUN+'</td>'+
								'<td class="content">'+items[i].CONTENT+'</td>'+
								'<td>'+items[i].MYONJUK+'</td>'+
								'<td>'+items[i].SOYOUJA_NAME+'</td>'+
								'<td>'+items[i].ADMIN_NAME+'</td>'+
								'<td>'+items[i].SIDAE+'</td>'+
								'<td>'+items[i].JIJUNG_DATE+'</td>'+
								'<td>'+items[i].ADDRESS1+'</td>'+
								'<td>'+items[i].UTMK_X+'</td>'+
								'<td>'+items[i].UTMK_Y+'</td>'+
								'<td><img src ="'+items[i].fileurl1+'" ></td>'+
								'<td><img src ="'+items[i].fileurl2+'" ></td>'+
								'<td><img src ="'+items[i].fileurl3+'" ></td>'+
							'</tr>';
		    		}
		    		
		    		
		    		
		    	

		    }
		};

		xhr.send('');
	}
	</script>
</body>
</html>

2)자바에서 넘기기

 

<%@ 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>
	<style>
		img {
			width:300px;
		}
		
	</style>
</head>
<body>
	<button onclick="f()">버튼</button>
	<table border='1' id="table">
		
		
	</table>
	<script>
	function f() {
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function () {
		    if (this.readyState == 4) {
		    	let datas =JSON.parse(this.responseText);
		    	console.log(datas.gyeongnamculturallist.body.items.item);
		    	
		    	let items = datas.gyeongnamculturallist.body.items.item;
		    	let tables =  document.querySelector('table');
		    	
		    	tables.innerHTML +=
    				'<tr>'+
						'<th>지정번호(세부)</th>'+
						'<th>명칭</th>'+
						'<th>명칭(한문)</th>'+
						'<th>문화재 설명</th>'+
						'<th>수량(면적)</th>'+
						'<th>소유자</th>'+
						'<th>관리자</th>'+
						'<th>시대구분</th>'+
						'<th>지정일</th>'+
						'<th>주소분류1</th>'+
						'<th>UTMKX좌표값</th>'+
						'<th>UTMKX좌표값</th>'+
						'<th>첨부파일1</th>'+
						'<th>첨부파일2</th>'+
						'<th>첨부파일3</th>'+
					'</tr>';
		    	
		    		for(let i =0; i<items.length; i++) {
		    			tables.innerHTML +=
		    				'<tr>'+
								'<td>'+items[i].DOJIJUNG_NO+'</td>'+
								'<td>'+items[i].MYONGCHING+'</td>'+
								'<td>'+items[i].MYONGCHING_HANMUN+'</td>'+
								'<td class="content">'+items[i].CONTENT+'</td>'+
								'<td>'+items[i].MYONJUK+'</td>'+
								'<td>'+items[i].SOYOUJA_NAME+'</td>'+
								'<td>'+items[i].ADMIN_NAME+'</td>'+
								'<td>'+items[i].SIDAE+'</td>'+
								'<td>'+items[i].JIJUNG_DATE+'</td>'+
								'<td>'+items[i].ADDRESS1+'</td>'+
								'<td>'+items[i].UTMK_X+'</td>'+
								'<td>'+items[i].UTMK_Y+'</td>'+
								'<td><img src ="'+items[i].fileurl1+'" ></td>'+
								'<td><img src ="'+items[i].fileurl2+'" ></td>'+
								'<td><img src ="'+items[i].fileurl3+'" ></td>'+
							'</tr>';
		    		}
		    		
		    }
		};
		xhr.open('GET',"GongGongServlet", true);
		xhr.send();
	}
	</script>
</body>
</html>
package servlets;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

import dao.GongGongDao;

@WebServlet("/GongGongServlet")
public class GongGongServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		GongGongDao gsc = new GongGongDao();
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		try {
			out.print(gsc.getSampleCode());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}
package dao;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class GongGongDao {
	public String getSampleCode() throws Exception{
        	StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/6480000/gyeongnamcultural/gyeongnamculturallist"); /*URL*/
        	urlBuilder = new StringBuilder("http://apis.data.go.kr/6480000/gyeongnamcultural/gyeongnamculturallist"); /*URL*/
            urlBuilder.append("?" + URLEncoder.encode("serviceKey","UTF-8") + "=%2Bt74wBuvAszqEeE9BKcwwW4MceBu4icZ6TP2u6KGnnIjxm%2FxHVRAl1CKQb5OKgW932n5357ZBdP78FrQnHOwAQ%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("10", "UTF-8")); /*한 페이지 결과 수*/
            urlBuilder.append("&" + URLEncoder.encode("resultType","UTF-8") + "=" + URLEncoder.encode("json", "UTF-8")); /*JSON방식으로 호출 시 파라미터 resultType=json 입력*/
            URL url = new URL(urlBuilder.toString());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-type", "application/json");
            System.out.println("Response code: " + conn.getResponseCode());
            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();
            return sb.toString();
        
	}
}