본문 바로가기
코딩수업/AWS 클라우드환경 네이티브

11/17 웹 제작 - 주소 검색 기능(Daum API) / 날짜 검색 기능

by 인생즐겜러 2022. 11. 28.
728x90
반응형

AWS 클라우드환경 네이티브 수업 123 일차

 

 

 

진행

1. 웹 제작 - 주소 검색 기능(Daum API)

2. 웹 제작 - 날짜 검색 기능

 

 

 

 

 

요약

1. 웹 제작 - 주소 검색기능(Daum API)

2. 웹 제작 - 날짜 검색 기능

 

 

 

 

 


 

 

 

 

 

웹 제작 - 주소 검색 기능(Daum API)

 

 

 

(1) 필수 DB 및 API

 

주소 DB를 제공하는 주소 이다.

 

https://business.juso.go.kr/addrlink/elctrnMapProvd/geoDBDwldPubList.do?cPath=99JD 

 

공개하는 주소

※ 도로명주소 공간정보의 건물객체는 국가주소정보시스템에서 최초 생성되며, 데이터가 일단위 갱신 관리되어 신속성과 정확성이 우수하므로 공간정보 구축 시 도로명주소를 위치식별자로

business.juso.go.kr

 

 

 

카카오에서 주소 DB api 를 무료제공하는 걸 이용한다.

 

http://postcode.map.daum.net/guide

 

Daum 우편번호 서비스

우편번호 검색과 도로명 주소 입력 기능을 너무 간단하게 적용할 수 있는 방법. Daum 우편번호 서비스를 이용해보세요. 어느 사이트에서나 무료로 제약없이 사용 가능하답니다.

postcode.map.daum.net

 

 

 

 

 

(2) topMenu.jsp View에 주소 검색을 위한 버튼 추가

 

<!-- topMenu.jsp에 코드추가 -->

<li role="presentation" class="divider"></li>
<li><a href="${contextPath}/util/address">주소 검색 (Daum API)</a></li>

 

 

 

 

 

(3) Controller 제작

 

 

 

util/address  에 해당하는 컨트롤러를 만든다.

그래야 View에서 만든 버튼을 클릭했을 때 다른 페이지(view/util/address 에 위치한 address.jsp)로 이동이 가능하므로.

 

// 컨트롤러

package com.edu.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.edu.main.HomeController;

//==============================================================
// public class UtilController
//==============================================================
@Controller
@RequestMapping("/util")
public class UtilController {
	
	private static final Logger logger = LoggerFactory.getLogger(UtilController.class);
	//==============================================================
	// 주소검색
	//==============================================================
	@RequestMapping(value="/address", method=RequestMethod.GET)
	public String address() throws Exception {
		
		logger.info("UtilController 주소검색 화면 불러오기");
		
		return "/util/address";
	}

}	// End - public class UtilController

 

 

 

 

 

(4) address.jsp 제작

 

new daum.Postcode는 다음에서 제공하는 API의 기능이다.

(자세한 코드 내용과 예시는 위에서 적은 http://postcode.map.daum.net/guide 카카오 홈페이지 참조하면 된다.)

 

<!-- address.jsp -->

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@	taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<%	
	// 다음 주소 검색 API ==> http://postcode.map.daum.net/guide
	request.setCharacterEncoding("UTF-8"); 
%>


<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>주소 검색(Daum API)</title>
</head>
<body>
	<!-- 상태 메뉴 -->
	<jsp:include page="../../common/topMenu.jsp" flush="false"/>
	
	<div class="container">
		<form class="form-horizontal" name="zipForm" method="post">
			<div class="form-group">
				<label class="col-sm-2" style="text-align:right">우편번호</label>
				<div class="col-sm-6">
					<input type="text" class="form-control" name="zipcode" id="zipcode" readonly/>
					<input type="button" class="form-control" onclick="daumZipCode()" value="우편번호검색"/>
				</div>
			</div>
			<div class="form-group">
				<label class="col-sm-2" style="text-align:right">주  소</label>
				<div class="col-sm-6">
					<input type="text" class="form-control" id="address01" name="address01"/>
				</div>
			</div>
			<div class="form-group">
				<label class="col-sm-2" style="text-align:right">상세주소</label>
				<div class="col-sm-6">
					<input type="text" class="form-control" id="address02" name="address02"/>
				</div>
			</div>
		</form>
	</div>
	
	
	<!-- 하단 메뉴 -->
	<jsp:include page="../../common/footer.jsp" flush="false"/>
</body>

<script src="//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js"></script>
<script>
	function daumZipCode() {
		new daum.Postcode({
			oncomplete: function(data) {
				// 팝업창에서 검색한 결과 중 항목을 클릭하였을 경우에 실행할 코드를 이곳에 작성한다.
				
				// 각 주소의 노출 규칙에 따라서 주소를 조합해야 한다.
				// 내려오는 변수가 값이 없는 경우에는 공백('') 값을 가지므로 이름을 참고하여 분기한다.
				let fullAddr = '';	// 최종 주소를 담을 변수
				let subAddr = '';	// 조합형 주소를 담을 변수
				
				// 사용자가 선택한 주소의 타입에 따라서 해당 주소값을 가져온다.
				if(data.userSelectedType == 'R') {	// 도로명 주소를 선택한 경우
					fullAddr = data.roadAddress;
				} else {	// 지번 주소를 선택한 경우
					fullAddr = data.jibunAddress;
				}
				
				// 사용자가 선택한 주소가 도로명 타입일 때 조합
				if(data.userSelectedType == 'R') {
					// 법정동명이 있을 경우에 추가한다.
					if(data.bname != '') {
						subAddr += data.bname;
					}
					// 건물명이 있을 경우에 추가한다.
					if(data.buildingName != '') {
						subAddr += (subAddr != '' ? ', ' + data.buildingName : data.buildingName);
					}
					// 조합형 주소의 유무에 따라 양쪽에 괄호를 추가하여 최종 주소를 만든다.
					fullAddr += (subAddr != '' ? '(' + subAddr + ')' : '');
				}
				
				// 우편번호와 주소정보를 화면의 해당 필드에 출력시킨다.
				// 5자리의 새 우편번호
				document.getElementById('zipcode').value = data.zonecode;
				document.getElementById('address01').value = fullAddr;
				
				// 커서를 상세주소 입력란으로 이동시킨다.
				document.getElementById('address02').focus();
				
				
			}	// End - oncomplete: function(data)
		
		}).open({
			// 우편번호 팝업 창이 여러개 뜨는것을 방지하기 위해 popupName을 사용한다.
			// 이거 안쓰면 버튼 누를때마다 주소입력 팝업 창 계속 뜸
			popupName: 'postcodePopup'
		});
	}	// End - function daumZipCode()
	
</script>

</html>

 

우편번호 쪽 readonly 를 설정해주면

아래처럼 해당 칸은 쓸 수가 없고 읽을 수만 있게 된다.

 

 

 

 

 

 

 

 


 

 

 

 

 

웹 제작 - 날짜 입력 기능

 

 

 

(1) topMenu.jsp View에 코드를 추가.

 

<!-- topMenu.jsp에 코드추가 -->

<li role="presentation" class="divider"></li>
<li><a href="${contextPath}/util/datepicker">날짜 검색</a></li>

 

 

 

 

 

(2) Controller 제작

 

View에서 util/datepicker 에 매칭되는 컨트롤러를 제작.

여기선 주소 검색하던 컨트롤러에 같이 메소드를 만들거다.

 

View에서 날짜검색 버튼을 클릭하면

view/util/datepicker 에 위치한 datepicker.jsp View 페이지로 넘어간다.

 

 

 

// public class UtilController 에 코드 추가
	
	//==============================================================
	// 날짜검색
	//==============================================================
	@RequestMapping(value="/datepicker", method=RequestMethod.GET)
	public String datepicker() throws Exception {
		
		logger.info("UtilController 날짜검색 화면 불러오기");
		
		return "/util/datepicker";
	}

 

 

 

 

 

(3) datepicker.jsp 제작

 

<!-- datepicker.jsp -->

<%@page import="org.apache.ibatis.reflection.SystemMetaObject"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@	taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page import="java.util.*" %>
<%@ page import="java.sql.Timestamp" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<%
	Calendar cal = Calendar.getInstance();
	request.setCharacterEncoding("UTF-8");
	Timestamp nowTime = new Timestamp(System.currentTimeMillis());
	int lastYear = cal.get(Calendar.YEAR);
	int lastMonth = cal.get(Calendar.MONTH) + 1;
	int lastDay = cal.get(Calendar.DATE);
	// int lastYear = Integer.parseInt(nowTime.toString().substring(0, 4));
	// int lastMonth = Integer.parseInt(nowTime.toString().substring(5, 7));
	// int lastDay = Integer.parseInt(nowTime.toString().substring(8, 10));
%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>날짜 검색</title>
</head>
<body>
	<!-- 상단 메뉴 -->
	<jsp:include page="../../common/topMenu.jsp" flush="false"/>
	<div><%=nowTime %></div>
	
	<div class="container">
		<form class="form-horizontal">
			<div class="form-group">
				<div>
					<h2 align="center">도서 정보</h2>
				</div>
			</div>
			<div class="form-group">
				<label class="control-label col-sm-2">출판일자</label>
				<div class="col-sm-2">
					<div class="input-group">
						<select class="form-control" name="publishing_year" style="width:100%" 
							onkeydown="nextFocus(publishing_month)">
							<%for(int i = lastYear; i>=2001; i--) { %>
							<option value="<%=i %>"><%=i %></option>
							<% } %>
						</select>
						<span class="input-group-addon">년</span>
					</div>
				</div>
				<div class="col-sm-2">
					<div class="input-group">
						<select class="form-control" name="publishing_month" style="width:100%" 
							onkeydown="nextFocus(publishing_day)">
							<%for(int i = 1; i<=12; i++) { %>
							<option value="<%=i %>" <c:if test="<%=i==lastMonth %>">selected</c:if>><%=i %></option>
							<% } %>
						</select>
						<span class="input-group-addon">월</span>
					</div>
				</div>
				<div class="col-sm-2">
					<div class="input-group">
						<select class="form-control" name="publishing_day" style="width:100%" 
							onkeydown="nextFocus(publishing_day)">
							<%for(int i = 1; i<=31; i++) { %>
								<option value="<%=i %>" <c:if test="<%=i==lastDay %>">selected</c:if>><%=i %></option>
							<% } %>
						</select>
						<span class="input-group-addon">일</span>
					</div>
				</div>
			</div>
		</form>
	</div>
	
	<hr/>

	<div class="container">
	   <form class="form-horizontal">
	      <div class="form-group">
	         <div>
	            <h2 align="center">게시글 상세 조회</h2>
	         </div>
	      </div>
	      <div class="form-group">
	         <label class="control-label col-sm-2">일자</label>
	         <div class="col-sm-2">
	            <input type="text" class=" form-control" id="datepicker1" placeholder="날짜를 선택하십시오."/>
	         </div>
	      </div>
	      <div class="form-group">
	         <label class="control-label col-sm-2">일자</label>
	         <div class="col-sm-2">
	            <input type="text" class=" form-control" id="datepicker2" placeholder="날짜를 선택하십시오."/>
	         </div>
	      </div>
	      <div class="form-group">
	         <label class="control-label col-sm-2">조회기간을 선택하세요.</label>
	         <div class="col-sm-2">
	            <input type="text" class=" form-control" id="datepicker3" placeholder="날짜를 선택하십시오."/>
	         </div>
	         <div class="col-sm-1">
	            &nbsp;~&nbsp;
	         </div>
	         <div class="col-sm-2">
	            <input type="text" class=" form-control" id="datepicker4" placeholder="날짜를 선택하십시오."/>
	         </div>
	      </div>
	   </form>
	</div>
	
	
	
	
</body>

<script>
	function nextFocus(where) {
		if(event.keyCode == 13) {
			where.focus();
		}
	}
</script>

<script>
$(function() {
   
   $("#datepicker1").datepicker();
   
   $("#datepicker2").datepicker({
      // 선택할 수 있는 최대 날짜 +1m +1w은 1달 1주일 뒤까지 선택이 가능하다. [+, -][숫자][y, m, w, d]
      maxDate:   "+1m +1w", 
      minDate:   "-1y"
   });
   
   $("#datepicker3, #datepicker4").datepicker({
      // 옵션들 생략
   });
   
});

$.datepicker.setDefaults({
   showOn:         "both",      // 버튼과 텍스트 필드 모두 캘린더를 보여준다.
   changeYear:      true,      // 년을 바꿀 수 있는 셀렉트 박스를 표시한다.
   changeMonth:   true,      // 월을 바꿀 수 있는 셀렉트 박스를 표시한다.
   showAnim:      "slide",   // 애니메이션을 적용한다.
   dateFormat:      'yy-mm-dd',   // 날짜 포맷.
   prevText:      '이전 달',   // 마우스 오버시 이전달이라는 텍스트 풍선도움말을 보여준다.
   nextText:      '다음 달',   // 마우스 오버시 다음달이라는 텍스트 풍선도움말을 보여준다.
   closeText:      '닫기',      // 닫기 버튼 텍스트 변경
   currentText:   '오늘',      // 
   monthNames:      ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'], // 월을 한글로 표시
   monthNamesShort:['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'], // 월을 한글로 표시
   dayNames:      ['일', '월', '화', '수', '목', '금', '토'],   // 주를 한글로 표시
   dayNamesShort:   ['일', '월', '화', '수', '목', '금', '토'],   // 주를 한글로 표시
   dayNamesMin:   ['일', '월', '화', '수', '목', '금', '토'],   // 주를 한글로 표시
   showMonthAfterYear:   true,   // true : 년 월   false : 월 일 순으로 보여준다.
   yearSuffix:      '년',
   showButtonPanel:   true   // 오늘로 가는 버튼과 달력 닫기 버튼 보기 옵션
});
</script>

</html>

 

 

 

만약 위의 jsp 파일에서

맨 아래 결과물의 맨 아래 부분과 같은 달력 스타일이나 datepicker 기능을 사용하고 싶다면

바로 아래의 코드를 쓰면 된다.

 

<!-- 달력 스타일 등이 들어있는 태그, datepicker 기능을 사용하려면 이 태그가 꼭 필요하다. -->
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<!--
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
이 태그보다 아래에 위치해야 한다.
현재 프로젝트에서 이 코드가 위치한 곳은 topMenu.jsp 이다.
-->

 

 

 

 

 

결과

 

 

728x90
반응형

댓글