티스토리 뷰

 

 

 

package com.springmvc.controller;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.jdom2.input.SAXBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.jdom2.Document;
import org.jdom2.Element;

@Controller
public class Jdom {
	@GetMapping("/sample")
	public String SampleApi(@RequestParam(defaultValue = "1") int page,Model model) throws Exception{
		StringBuilder urlBuilder = new StringBuilder("https://apis.data.go.kr/B551182/hospInfoServicev2/getHospBasisList");

        urlBuilder.append("?ServiceKey=인증키");
        //urlBuilder.append("&pageNo=6");
        urlBuilder.append("&numOfRows=10");
        urlBuilder.append("&dgsbjtCd=05");
        urlBuilder.append("&page=" + page);  // 페이지 번호 추가

        URL url = new URL(urlBuilder.toString());

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/xml");
        //conn.connect();

        System.out.println("Response code: " + conn.getResponseCode());
        
        SAXBuilder builder = new SAXBuilder();
        String queryTime = "";
        Document document = builder.build(conn.getInputStream());
        Element root = document.getRootElement();
        List xmlelement = root.getChildren();
        Iterator it = xmlelement.iterator();
        
        List headerList = null;
        List bodyList = null;
        List itemsList = null;
        List itemList = null;
            
        
        while(it.hasNext()) {  //반복반복이터레이터돌림
        	Element e = (Element)it.next();
        	System.out.println(e.getName());
        	
        	if(e.getName()=="header") {
        		headerList = e.getChildren();
        	}
        	if(e.getName()=="body") {
        		bodyList = e.getChildren();
        	}
        	if(e.getName()=="items") {
        		itemsList=e.getChildren();
        	}
        }
        
        System.out.println("<header>");
        Iterator headerIt = headerList.iterator();
        
        while(headerIt.hasNext()) {
        	Element e = (Element)headerIt.next();
        	System.out.println(e.getName()+" : "+e.getValue());
        	
        }
        
        System.out.println("<body>");
        Iterator bodyIt = bodyList.iterator();
        
        while(bodyIt.hasNext()) {
        	Element e = (Element)bodyIt.next();
        	System.out.println(e.getName()+" : "+e.getValue());
        	if(e.getName()=="items") {
        		itemsList = e.getChildren();
        	}
        }
        
        
        System.out.println("<items>");
        Iterator itemsIt = itemsList.iterator();
        while(itemsIt.hasNext()) {
        	Element e = (Element)itemsIt.next();
        	System.out.println(e.getName()+" : "+e.getValue());
        	if(e.getName()=="item") {
        		itemList = e.getChildren();
        	}
        }
        
        System.out.println("<item>");
        HashMap<String, String> resultMap = new HashMap<>();
        Iterator itemIt = itemList.iterator();
        while(itemIt.hasNext()) {
        	Element e = (Element)itemIt.next();
        	System.out.println(e.getName()+" : "+e.getValue());
        	resultMap.put(e.getName(), e.getValue());
        }
        
        int totalItemCount = Integer.parseInt(root.getChild("body")
                .getChild("totalCount")
                .getValue());
        model.addAttribute("totalItemCount", totalItemCount);
        
        model.addAttribute("response",resultMap);
        return "/Hospital/index";
	}
	
	
}

 

 

 

이 코드를 실행 했을 때는 맨 마지막 값만 저장되어 계속 출력되었다.

아래는 첫번째 코드를 실행했을 때 출력되는 콘솔과 뷰 페이지의 모습이다.

 

 

 

 

 

 

 

두번째 수정 코드

 

package com.springmvc.controller;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom2.input.SAXBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.jdom2.Document;
import org.jdom2.Element;

@Controller
public class Jdom {
	@GetMapping("/sample")
	public String SampleApi(@RequestParam(defaultValue = "1") int page,Model model) throws Exception{
		
		
		StringBuilder urlBuilder = new StringBuilder("https://apis.data.go.kr/B551182/hospInfoServicev2/getHospBasisList");

        urlBuilder.append("?ServiceKey=인증키");
        //urlBuilder.append("&pageNo=6");
        urlBuilder.append("&numOfRows=10");
        urlBuilder.append("&dgsbjtCd=05");
        urlBuilder.append("&page=" + page);  // 페이지 번호 추가

        URL url = new URL(urlBuilder.toString());

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/xml");
        //conn.connect();

        System.out.println("Response code: " + conn.getResponseCode());
        
        SAXBuilder builder = new SAXBuilder();
        String queryTime = "";
        Document document = builder.build(conn.getInputStream());
        Element root = document.getRootElement();
        List xmlelement = root.getChildren();
        Iterator it = xmlelement.iterator();
        
        List headerList = null;
        List bodyList = null;
        List itemsList = null;
        List<Element> itemList = null;
            
        
        while(it.hasNext()) {  //반복반복이터레이터돌림
        	Element e = (Element)it.next();
        	System.out.println(e.getName());
        	
        	if(e.getName()=="header") {
        		headerList = e.getChildren();
        	}
        	if(e.getName()=="body") {
        		bodyList = e.getChildren();
        	}
        	if(e.getName()=="items") {
        		itemsList=e.getChildren();
        	}
        }
        
        System.out.println("<header>");
        Iterator headerIt = headerList.iterator();
        
        while(headerIt.hasNext()) {
        	Element e = (Element)headerIt.next();
        	System.out.println(e.getName()+" : "+e.getValue());
        	
        }
        
        System.out.println("<body>");
        Iterator bodyIt = bodyList.iterator();
        
        while(bodyIt.hasNext()) {
        	Element e = (Element)bodyIt.next();
        	System.out.println(e.getName()+" : "+e.getValue());
        	if(e.getName()=="items") {
        		itemsList = e.getChildren();
        	}
        }
        
        
        List<Map<String, String>> dataList = new ArrayList<>();
        System.out.println("<items>");
        Iterator itemsIt = itemsList.iterator();
        while (itemsIt.hasNext()) {
            Element e = (Element) itemsIt.next();
            System.out.println(e.getName() + " : " + e.getValue());

            if ("item".equals(e.getName())) {
                itemList = e.getChildren();
                Map<String, String> dataMap = new HashMap<>();  // 각각의 <item> 요소마다 새로운 Map을 생성
                for (Element itemElement : itemList) {
                    System.out.println(itemElement.getName() + " : " + itemElement.getValue());
                    dataMap.put(itemElement.getName(), itemElement.getValue());
                }
                dataList.add(dataMap);
            }
        }
        
		/*
		 * System.out.println("<item>"); HashMap<String, String> resultMap = new
		 * HashMap<>(); Iterator itemIt = itemList.iterator(); while(itemIt.hasNext()) {
		 * Element e = (Element)itemIt.next();
		 * System.out.println(e.getName()+" : "+e.getValue());
		 * resultMap.put(e.getName(), e.getValue()); }
		 */
        
        int totalItemCount = Integer.parseInt(root.getChild("body")
                .getChild("totalCount")
                .getValue());
        model.addAttribute("totalItemCount", totalItemCount);
        // Model 객체를 사용하여 데이터를 저장
        model.addAttribute("dataList", dataList);
        //model.addAttribute("response",resultMap);
        return "/Hospital/index";
	}
	
	
}

 

 

 

위와 같이 수정을 한 후 실행한 결과는 아래와 같이 정상적으로 출력되는 모습을 볼 수 있었다.

 

 

 

 

이 두개의 코드는 비슷해보이지만 데이터를 처리하고 저장하는 방식에 차이가 존재했다.

 

첫번째 코드는 직접 원하는 <item> 요소에 접근해 데이터를 추출하고 저정하는 코드이다.

HashMap<String, String> resultMap 에 데이터가 즉시 저장되고 이 데이터를 모델에 추가한다.

그러므로 이 코드는 모델에 최종 마지막 결과만 저장하도록 작성되어 <item>에 대한 데이터를 개별적으로 추출해 리스트에 담고 있지 않다.

쉽게 말해 <item>에 대한 데이터를 반복할때 마다 resultMap 에 덮어씌우며 저장을 하여 마지막 값만 추출되는 것이다.

 

 

두번째 코드는 각 요소들을 순회하여 데이터를 추출해 List<Map<String,String>> dataList 에 저장한다.

이때 각 <item> 요소마다 새로운 Map<String, String>이 생성되어 데이터가 저장된다. 

이렇게 코드가 작성되어 실행될때는 <item>에 대한 데이터를 리스트에 담을 수 있다.

 

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday