우편번호 API를 사용하기 위해서 우체국 홈페이지에서 

API 사용신청을 합니다.


사용신청하기



신청하시게되면 인증키가 나올꺼에요. 

인증키는 따로 복사해둡니다.



저는 부트스트랩 모달을 이용해 팝업을 띄울꺼예요.



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
<div class = "row">
        <div class = "col-md-4">
            <div class = "input-group">
                <span class = "input-group-addon">우편번호</span>
                <input type = "text" class = "form-control" id = "zip_code" name = "zip_code">
                <span class = "input-group-addon"><a href = "#" id = "zip_codeBtn" data-toggle="modal" data-target="#zip_codeModal">검색하기</a></span>                
            </div>
        </div>
    </div>
    <div class = "row">
        <div class = "col-md-4">
            <div class = "input-group">
                <span class = "input-group-addon">주소</span>
                <input type = "text" class = "form-control" id = "address1">                
            </div>
        </div>
    </div>        
    <div class = "row">
        <div class = "col-md-4">
            <div class = "input-group">
                <span class = "input-group-addon">상세주소</span>
                <input type = "text" class = "form-control" id = "address2">        
            </div>
        </div>
    </div>    
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
<div class="modal fade" id="zip_codeModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header text-center">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
                <h3 class="modal-title" id="myModalLabel">우편번호</h3>
            </div>    
            <div class="modal-body text-center">
                 <form id = "zip_codeForm">
                         <div class = "input-group">
                            <span class = "input-group-addon">동 입력</span>
                            <input type="text" class = "form-control" name="query" id="query">
                            <span class = "input-group-btn">                                                
                                <input type="submit" class = "btn btn-warning" value="검색" id="searchBtn" onkeydown="javascript:if(event.keyCode==13)">                                            
                            </span>
                        </div>
                </form>
                <p>
                </p>
                <div>
                <div style="width:100%; height:200px; overflow:auto">
                       <table class = "table text-center">
                        <thead>
                            <tr>
                                <th style="width:150px;">우편번호</th>
                                <th style="width:600px;">주소</th>
                                </tr>
                        </thead>
                        <tbody id="zip_codeList"></tbody>
                    </table>
                </div>
                </div>
            </div>
        </div>
    </div>
</div>
cs


이젠 스크립트를 짤겁니다. modal창으로 켰기때문에 ajax로 데이터를 바로 받아왔습니다.


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
<script>
$(function(){
    // 검색버튼 눌렸을 때 함수 실행
    $("#searchBtn").click(function(e){
        e.preventDefault();
        // ajax
        $.ajax({
            // zip_codeList controller 진입 url
            url : "zip_codeList",
            // zip_codeForm을 serialize 해줍니다.
            data : $("#zip_codeForm").serialize(),
            type : "POST",
            // dataType 은 json형태로 보냅니다.
            dataType : "json",
            success : function(result){
                $("#zip_codeList").empty();
                var html = "";
                if(result.errorCode != null && result.errorCode != ""){
                    html += "<tr>";
                    html += "    <td colspan='2'>";
                    html +=            result.errorMessage;
                    html += "    </td>";
                    html += "</tr>";
                }
                else{
                    // 검색결과를 list에 담는다.
                    var list = result.list;
                    
                    for(var i = 0; i < list.length; i++){
                        html += "<tr>";
                        html += "    <td>";
                        // 우편번호
                        var zipcode = list[i].zipcode;
                        // 주소
                        var address = list[i].address;
 
                        html +=         list[i].zipcode;
                        html += "    </td>";
                        html += "    <td>";
                        html +=     '<a href="#" onclick="put(\'' + list[i].address + '\',\'' + zipcode + '\')">' + address + '</a>';
                        html += "    </td>";
                        html += "</tr>";
                    }
                }
                // 완성된 html(우편번호 list)를 zip_codeList밑에 append
                $("#zip_codeList").append(html);
            }
        });
    });
});
 
// 원하는 우편번호 선택시 함수 실행
function put(address,zipcode){
    var address = address;
    var zipcode = zipcode;
    // 모달창 닫기
    $("#zip_codeModal").modal("hide");
    $("#zip_code").val(zipcode);
    $("#address1").val(address);
}
 
</script>
cs



주석은 최대한 달아놓았고 스크립트 부분은 쉬우니 설명은 패스하겠습니다.



우편번호를 리턴받기 위해서는 Jsoup 와 Gson이 필요합니다. dependency에 추가해줍니다.


1
2
3
4
5
6
7
8
9
10
11
12
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.8.3</version>
    </dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.2.4</version>
    </dependency>
cs



추가 후 우편번호와 주소를 담을 VO 생성을 합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package slit.erp.domain;
 
public class zip_codeVO {
    private String address; // 주소
    private String zipcode; // 우편번호
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getZipcode() {
        return zipcode;
    }
    public void setZipcode(String zipcode) {
        this.zipcode = zipcode;
    }
    
    
}
 
cs



이제 controller를 작성하겠습니다.


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
// 인증키
    public static final String ZIPCODE_API_KEY = "";
    // api를 쓰기 위한 주소
    public static final String ZIPCODE_API_URL = "http://biz.epost.go.kr/KpostPortal/openapi";
    @RequestMapping(value = "/zip_codeList", method = RequestMethod.POST, produces = "text/planin;charset=UTF-8")
    public @ResponseBody String zip_codeList(@RequestParam("query"String query) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuilder queryUrl = new StringBuilder();
        queryUrl.append(ZIPCODE_API_URL);
        queryUrl.append("?regkey=");
        queryUrl.append(ZIPCODE_API_KEY);
        queryUrl.append("&target=");
        queryUrl.append("postNew");
        queryUrl.append("&query=");
        queryUrl.append(query.replaceAll(" """));
        
        // document 선언
        Document document = Jsoup.connect(queryUrl.toString()).get();
        // errorCode 선언
        String errorCode = document.select("error_code").text();
        
        if(null == errorCode || "".equals(errorCode))
        {
            Elements elements = document.select("item");
            List<zip_codeVO> list = new ArrayList<zip_codeVO>();
            zip_codeVO zip_codeVO = null;
            
            for(Element element : elements){
                zip_codeVO = new zip_codeVO();
                zip_codeVO.setZipcode(element.select("postcd").text());
                // 지번 검색
                zip_codeVO.setAddress(element.select("address").text());
                list.add(zip_codeVO);
            }
            // list 결과 put
            paramMap.put("list", list);
        }else{
            String errorMessage = document.select("message").text();
            paramMap.put("errorCode", errorCode);
            paramMap.put("errorMessage", errorMessage);
        }
        // Gson형태로 paramMap 리턴
        return (new Gson()).toJson(paramMap);
    }

cs

 




결과화면




주소 선택 시 put 함수가 실행될꺼니 결과는 아래와같이 잘 삽입되는것을 보실 수 있으실꺼에요.