Notice
Recent Posts
Recent Comments
Link
«   2026/03   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

brograming

공공데이터 활용 url로 정보 가져오기(Weather)_Day43 본문

Kosta

공공데이터 활용 url로 정보 가져오기(Weather)_Day43

brograming 2023. 4. 19. 00:02

index

<body>
<h3>공공데이터 활용</h3>
<a href= "${pageContext.request.contextPath }/csv/load.do">csv 데이터 확인</a><br/>
<a href= "${pageContext.request.contextPath }/json/load.do">json 데이터 확인</a><br/>
<a href= "${pageContext.request.contextPath }/xml/load.do">xml 데이터 확인</a><br/>
<a href= "${pageContext.request.contextPath }/weather/load.do">기상청 날씨 데이터 확인</a><br/>
<form action = "${pageContext.request.contextPath }/bus/load.do" method = "post">
버스 정보 확인 : <input type = "text" name = "busid">
<input type = "submit" value = "검색">
</form>
<form action = "${pageContext.request.contextPath }/bus/getlistbyName.do" method = "post">
검색할 버스번호 : <input type = "text" name = "busnm">
<input type = "submit" value = "검색">
</form>
</body>

commands.properties

/csv/load.do=handler.CsvHandler
/json/load.do=handler.JsonHandler
/xml/load.do=handler.XmlHandler
/weather/load.do=handler.WeatherRssHandler
/bus/load.do=handler.BusRouteInfoHandler
/bus/getlistbyName.do=handler.BusListByNameHandler
/bus/stationlist.do=handler.StationListHandler

 

▼WeatherVo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package xml;
 
public class WeatherVo {
    private String city;
    private String dateTime;
    private String info;
    private String tmn; // 최저온도
    private String tmx; // 최고온도
    private String rnst; // 비올 확률
    
    public WeatherVo() {}
 
    public WeatherVo(String city, String dateTime, String info, String tmn, String tmx, String rnst) {
        super();
        this.city = city;
        this.dateTime = dateTime;
        this.info = info;
        this.tmn = tmn;
        this.tmx = tmx;
        this.rnst = rnst;
    }
 
    public String getCity() {
        return city;
    }
 
    public void setCity(String city) {
        this.city = city;
    }
 
    public String getDateTime() {
        return dateTime;
    }
 
    public void setDateTime(String dateTime) {
        this.dateTime = dateTime;
    }
 
    public String getInfo() {
        return info;
    }
 
    public void setInfo(String info) {
        this.info = info;
    }
 
    public String getTmn() {
        return tmn;
    }
 
    public void setTmn(String tmn) {
        this.tmn = tmn;
    }
 
    public String getTmx() {
        return tmx;
    }
 
    public void setTmx(String tmx) {
        this.tmx = tmx;
    }
 
    public String getRnst() {
        return rnst;
    }
 
    public void setRnst(String rnst) {
        this.rnst = rnst;
    }
 
    @Override
    public String toString() {
        return "WeatherVo [city=" + city + ", dateTime=" + dateTime + ", info=" + info + ", tmn=" + tmn + ", tmx=" + tmx
                + ", rnst=" + rnst + "]";
    }
    
    
}
cs

▼WeatherRssHandler.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package handler;
 
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
 
import xml.WeatherVo;
 
public class WeatherRssHandler implements Handler {
 
    @Override
    public String process(HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        String urlstr = "http://www.kma.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=109";
        try {
            URL url = new URL(urlstr);  //url 객체 생성. URL : 웹 주소를 클래스화 
            URLConnection conn = url.openConnection(); // 네트워크 연결. URLConnection conn : 주소에 연결된 객체
            
//            //데이터 읽기 테스트
//             //conn.getInputStream() : 저 url에 연결된 자원을 읽을 읽기 스트림 반환
//            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8")); 
//            StringBuilder sb = new StringBuilder();
//            String str="";
//            while((str=br.readLine())!=null){
//                
//                sb.append("\n" + str);  // 웹페이지에서 한줄한줄 읽은 것을 sb에 넣어둠
//            }
//            str=sb.toString();
//            System.out.println(str); // 읽어온 내용을 한꺼번에 출력해서 확인해본다.
//            br.close();
            
            
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            
            //DocumentBuilder 객체 생성
            DocumentBuilder builder = factory.newDocumentBuilder();
            
            //xml 파싱
            Document doc = builder.parse(conn.getInputStream()); // 읽어온 데이터를 dom으로 
            
            Element root = doc.getDocumentElement(); //root 요소 추출
            String author = root.getElementsByTagName("author").item(0).getTextContent();//list를 반환하니까
            String category = root.getElementsByTagName("category").item(0).getTextContent();
            String title = root.getElementsByTagName("title").item(1).getTextContent();
        
            System.out.println("author: " + author);
            System.out.println("category: " + category);
            System.out.println("title: " + title);
            
            
            ArrayList<WeatherVo> list = new ArrayList<>();
            NodeList locs = root.getElementsByTagName("location");
            for(int i = 0; i < locs.getLength(); i++) {
                Element loc = (Element)locs.item(i);
                String city = loc.getElementsByTagName("city").item(0).getTextContent();
                NodeList datas = loc.getElementsByTagName("data");
                for(int j=0; j<datas.getLength(); j++) {
                    Element data = (Element) datas.item(j);
                    String dateTime = data.getElementsByTagName("tmEf").item(0).getTextContent();
                    String info = data.getElementsByTagName("wf").item(0).getTextContent();
                    String tmn = data.getElementsByTagName("tmn").item(0).getTextContent();
                    String tmx = data.getElementsByTagName("tmx").item(0).getTextContent();
                    String rnst = data.getElementsByTagName("rnSt").item(0).getTextContent();
                    list.add(new WeatherVo(city, dateTime, info, tmn, tmx, rnst));
                }
            }
            
            request.setAttribute("list", list);
            request.setAttribute("author", author);
            request.setAttribute("category", category);
            request.setAttribute("title", title);
            System.out.println(list);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "/xml/weatherlist.jsp";
    }
    
 
}
cs

▼weatherlist.jsp

<body>

<h3>${title }</h3>

<h4>${category } (author:${author })</h4>

 

<table border="1">

<tr><th>city</th><th>dateTime</th><th>info</th><th>tmn</th><th>tmx</th><th>rnst</th></tr>

<c:forEach var = "vo" items="${list }" varStatus="status"> <%-- // varStatus : for문에 대한 상태값을 갖는 변수. 변수 이름 : status로 설정 --%>

<tr>

<c:if test ="${status.index%13 == 0 }">

<td rowspan= "13">${vo.city }</td>

</c:if>

<td>${vo.dateTime }</td><td>${vo.info }</td><td>${vo.tmn }</td><td>${vo.tmx }</td><td>${vo.rnst }</td></tr>

</c:forEach>

 

 

</table>

</body>

'Kosta' 카테고리의 다른 글

[Spring]05_09  (0) 2023.05.10
[Spring] 05_08  (0) 2023.05.08
공공데이터 활용 url로 정보 가져오기(Bus)_Day43  (0) 2023.04.18
csv, json, xml 공공데이터 활용 및 parsing_Day42  (0) 2023.04.17
JQUERY_Day40  (0) 2023.04.13