업무관련/스프링

juso.go.kr 제공하는 도로명 주소 api를 사용하여 찾기 Spring

레임보우 2023. 3. 31. 15:00

 

모달을 이용하여 주소입력과 버튼을 만듬

 



 
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
    function fn_getAddress(pageNo,isfirst) {
        console.log("fn_getAddress");
        console.log(pageNo+":"+isfirst);
        // 조회조건
        let keyword = $("#keyword").val();
        // 주소검색
        $.ajax({
            url:"${contextPath }/buyorder/getjuso",
            type : "post",
            data:{"keyword":keyword, // 주소 검색입력
                "pageNo":pageNo, // 검색결과의 페이지
                "isfirst":isfirst // 첫 검색인지
            },
            dataType:"json",
            crossDomain:true,
            success:function(jsonStr) {
                $("#list").html("");
                
                if (jsonStr != null) {
                    let errCode = jsonStr.results.common.errorCode;
                    let errDesc = jsonStr.results.common.errorMessage;
                    if(errCode != "0") {
                        alartpopup(errCode + ":" + errDesc);
                    } else {
                        fn_makeListJson(jsonStr);
                    }
                }
            },
            error:function(xhr, status, error) {
                alartpopup("정상적으로 조회되지 않았습니다.");
            }
        });
    }
cs
 
주소 검색 버튼을 누르면 fn_getAddress 호출
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    @RequestMapping(value = "/getjuso",method = RequestMethod.POST)
    public void getjuso(HttpServletRequest req, HttpServletResponse response) {
        System.out.println("getjuso");
        
        // 요청변수설정
        String keyword = req.getParameter("keyword");
        String pageNo = req.getParameter("pageNo");
        String isfirst = req.getParameter("isfirst");
        
        try {
            response=buyOrderService.GetJuso(keyword,pageNo, response ,Integer.parseInt(isfirst));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
cs
 
 
컨트롤러단에서 받아서 서비스단으로 전달
 
 
 



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
    private int firstTotalPage=1;
    
    @Override
    public HttpServletResponse GetJuso(String sreachJuso,String pageNoString, HttpServletResponse response,int isfirst) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("getjuso");
        // 요청변수설정
        String currentPage = pageNoString;// req.getParameter("currentPage");
        String countPerPage = "6";// req.getParameter("countPerPage");
        String resultType = "json";// req.getParameter("resultType");
        String confmKey = "U01TX0F*********************MzA0NjM=";// req.getParameter("confmKey");
        String keyword = sreachJuso;
        
        // 페이지가 넘어가는 문제가 있어 처음을 제외한 다음은 처음 받아왔던 total기준으로 페이지를 받고 넘어가지 못하게 함
        PagingInfo addrBoxPage = new PagingInfo();
        if(isfirst==0) {
            String testp = addrBoxPage.settingPage(firstTotalPage, 65,Integer.parseInt(pageNoString)); // 한페이지에 8개 게시물, 최대 5(<<12345>>)개 페이징갯수
            System.out.println(testp);
            currentPage=Integer.toString(addrBoxPage.getCurrentPos());
        }
        System.out.println(keyword);
        // API 호출URL 정보설정
        String apiUrl = "http://www.juso.go.kr/addrlink/addrLinkApi.do?currentPage=" + currentPage + "&countPerPage="
                + countPerPage + "&keyword=" + URLEncoder.encode(keyword, "UTF-8"+ "&confmKey=" + confmKey
                + "&resultType=" + resultType;
        URL url = new URL(apiUrl);
        BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
        StringBuffer sb = new StringBuffer();
        String tempStr = null;
        while (true) {
            tempStr = br.readLine();
            
            if (tempStr == null)
                break;
            sb.append(tempStr); // 응답결과XML 저장
        }
        br.close();
        //{"results":{"common":{"errorMessage":"정상","countPerPage":"10","totalCount":"45","errorCode":"0","currentPage":"1"}
        // https://studyingazae.tistory.com/196 참고함
        JSONParser parser = new JSONParser();
        Object Obj = parser.parse(sb.toString());
        JSONObject jsonObj = (JSONObject)Obj;
        JSONObject jsonResults =  (JSONObject)jsonObj.get("results"); // json에 result 안에
        jsonResults =  (JSONObject)jsonResults.get("common"); //  result 안에 또 common 안에
        System.out.println("errorMessage :"+jsonResults.get("errorMessage")); // 만약 못찾을때는 "null" 문자열로 내보냄
        System.out.println("countPerPage :" +jsonResults.get("countPerPage"));
        System.out.println("totalCount :"+jsonResults.get("totalCount"));
 
        // page 기능 구현
        if(isfirst==1) {
            int pageNo=Integer.parseInt((String)jsonResults.get("currentPage"));
            int total=Integer.parseInt((String)jsonResults.get("totalCount"));
            int postSize=Integer.parseInt((String)jsonResults.get("countPerPage"));
            firstTotalPage = total;
            System.out.println("pageNo : "+pageNo);
            String testp = addrBoxPage.settingPage(total, postSize, 5, pageNo); // 한페이지에 8개 게시물, 최대 5(<<12345>>)개 페이징갯수
            System.out.println(testp);
        }
    
        // 페이징 포지션 값 추가하여 json 문자열 전달
        jsonObj.put("startPage",Integer.toString(addrBoxPage.getStartPos()));
        jsonObj.put("currentPage",Integer.toString(addrBoxPage.getCurrentPos()));
        jsonObj.put("endPage",Integer.toString(addrBoxPage.getEndPos()));
        
        System.out.println(jsonObj.toJSONString());
        
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        System.out.println(sb.toString()); // 응답결과반환
        response.getWriter().write(jsonObj.toJSONString()); // 응답결과반환
 
        return response;
    }
cs




한페이지에 6개만 출력할거기 때문에 6을 고정으로 하였음

 
반환한 데이터를 페이징 처리해줘야 하기 때문에 

주소홈에서 받은 json데이터 중 필요한 데이터만 가져오기 위해 SimpleJson을 사용하였음
 
가져온 전체 결과값과 현재 페이지 위치를 계산하여 Json에 같이 합쳐버림
 
 
 
 




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
    function fn_makeListJson(jsonStr) {
        //console.log(jsonStr);
        //console.log(jsonStr.startPage+" ! "+jsonStr.currentPage+" ! "+jsonStr.endPage);
        
        let htmlStr = "";
 
        if (jsonStr.results.common.totalCount == "0") {
            htmlStr += "<table><tr><td>검색 결과가 없습니다</td></tr></table>"
            $("#findJusoList").html(htmlStr);
            return;
        }
        
        htmlStr += "<table>";
        htmlStr += "<tr>";
        htmlStr += "<td style='border-bottom: 1px solid #000; width:80px; text-align:center;'>순번</td>";
        htmlStr += "<td style='border-bottom: 1px solid #000; width:90%; text-align:center;'>주소</td>";
        htmlStr += "</tr>";
        
        
        $(jsonStr.results.juso).each(function(index) {
            htmlStr += "<tr>";
            htmlStr += "<td style='border-bottom: 1px solid #000; width:40px; text-align:center;'>" + (((jsonStr.currentPage-1)*6)+index+1) + "</td>";
            htmlStr += "<td style='border-bottom: 1px solid #000; text-align:left;'>";
            htmlStr +=  this.zipNo + "<br>";
            htmlStr +="<a href='#;' onClick='chooseJuso(\""+this.zipNo+"\",\""+this.roadAddr+"\");'>"+ this.roadAddr + "</a><br>";
            htmlStr += this.jibunAddr;
            htmlStr += "</td>";
            htmlStr += "</tr>";
        });
        
        htmlStr += "</table>";
        
        
        htmlStr += '<nav class="blog-pagination justify-content-center d-flex">';
        htmlStr +='<ul class="pagination">';
        htmlStr +='<li class="page-item"><a href="#;" id="pageLeft" onclick="fn_getAddress('+(Number(jsonStr.currentPage)-Number(5))+',0);" class="page-link" aria-label="Previous"> <span aria-hidden="true"> <span class="lnr lnr-chevron-left"></span>';
        htmlStr +='</span>';
        htmlStr +='</a></li>';
        
        
        for(let i=Number(jsonStr.startPage); i<=Number(jsonStr.endPage);i++){
            
            if(i==Number(jsonStr.currentPage)){
                
                htmlStr +='<li class="page-item active"><a href="#;" onclick="fn_getAddress('+i+',0);" class="page-link">'+i+'</a></li>';
            }else{
                
                htmlStr +='<li class="page-item"><a href="#;" onclick="fn_getAddress('+i+',0);" class="page-link">'+i+'</a></li>';
            }
            
        }
        
        htmlStr +='<li class="page-item"><a href="#;" id="pageRight" onclick="fn_getAddress('+(Number(jsonStr.currentPage)+Number(5))+',0);" class="page-link" aria-label="Next"> <span aria-hidden="true"> <span class="lnr lnr-chevron-right"></span>';
        htmlStr +='</span>';
        htmlStr +='</a></li>';
        htmlStr +='</ul>';
        htmlStr +='</nav>';
        
        
        $("#findJusoList").html(htmlStr);
    }
cs
 
 

 

ajax로 받은 데이터를 html에 입력하는 부분

 

 

 

 

 

 


 

이런식으로 검색결과를 나오게함