1.주소검색 model1
폴더구성
context.xml
<?xml version= "1.0" encoding="utf-8" ?>
<Context>
<Resource
name="jdbc/oracle"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:orcl"
username="scott"
password="tiger"
maxTotal="20"
maxWaitMillis="5000" />
</Context>
ZipTO
package model1;
public class ZipTO {
private String seq;
private String zipcode;
private String sido;
private String gugun;
private String dong;
private String ri;
private String bunji;
public String getSeq() {
return seq;
}
public void setSeq(String seq) {
this.seq = seq;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getSido() {
return sido;
}
public void setSido(String sido) {
this.sido = sido;
}
public String getGugun() {
return gugun;
}
public void setGugun(String gugun) {
this.gugun = gugun;
}
public String getDong() {
return dong;
}
public void setDong(String dong) {
this.dong = dong ;
}
public String getRi() {
return ri;
}
public void setRi(String ri) {
this.ri = ri;
}
public String getBunji() {
return bunji;
}
public void setBunji(String bunji) {
this.bunji = bunji;
}
}
ZipDAO
package model1;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class ZipDAO {
private DataSource dataSource;
public ZipDAO() {
try {
Context initCtx = new InitialContext();
Context envCtx = (Context)initCtx.lookup("java:comp/env");
dataSource = (DataSource)envCtx.lookup("jdbc/oracle");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ArrayList<ZipTO> zipList(String dong) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList<ZipTO> zipLists = new ArrayList<>();
try {
conn = dataSource.getConnection();
String sql = "select seq, zipcode, sido, gugun, dong, ri, bunji from zipcode where dong like ? order by seq";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, dong + "%");
rs = pstmt.executeQuery();
while(rs.next()) {
ZipTO to = new ZipTO();
to.setSeq(rs.getString("seq"));
to.setZipcode(rs.getString("zipcode"));
to.setSido(rs.getString("sido"));
to.setGugun(rs.getString("gugun"));
to.setDong(rs.getString("dong"));
to.setRi(rs.getString("ri") == null ? "" : rs.getString("ri"));
to.setBunji(rs.getString("bunji") == null ? "" : rs.getString("bunji"));
zipLists.add(to);
}
} catch(SQLException e) {
System.out.println(e.getMessage());
} finally {
if(rs != null) try { rs.close(); } catch(SQLException e ) {}
if(pstmt != null) try { pstmt.close(); } catch(SQLException e) {}
if(conn != null) try { conn.close(); } catch(SQLException e) {}
}
return zipLists;
}
}
data.jsp
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true" %>
<%@ page import="model1.ZipTO"%>
<%@ page import="model1.ZipDAO"%>
<%@ page import="java.util.ArrayList"%>
<%
request.setCharacterEncoding("utf-8");
String strDong = "신사";
if(request.getParameter("strDong") != null) {
strDong = request.getParameter("strDong");
}
StringBuffer result = new StringBuffer();
ZipDAO dao = new ZipDAO();
ArrayList<ZipTO> ziplist = dao.zipList(strDong);
for(int i=0 ; i<ziplist.size() ; i++) {
ZipTO to = ziplist.get(i);
String seq = to.getSeq();
String zipcode = to.getZipcode();
String sido = to.getSido();
String gugun = to.getGugun();
String dong = to.getDong();
String ri = to.getRi();
String bunji = to.getBunji();
result.append(seq + ",");
result.append(zipcode + ",");
result.append(sido + ",");
result.append(gugun + ",");
result.append(dong + ",");
result.append(ri + ",");
result.append(bunji + "\n");
}
%>
<%=result %>
ZipSearch.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
ul {list-style-type: none; overflow: hidden; margin: 0px; padding: 0px;}
li {border:1px solid #000000; float: left; padding: 5px;}
.header {background-color: #99ff99; text-align: center;}
.zipcode, .sido, .gugun, .dong, .ri, .bunji {
width: 100px;
height: 20px;
text-align: center;
}
.ri, .bunji { width: 200px;}
</style>
<script>
window.onload =function(){
document.getElementById('btn').onclick = function(){
//Ajax객체 생성
var request = new XMLHttpRequest();
//요청 상태변화를 확인하고 응답텍스트를 출력
request.onreadystatechange = function(){
if(request.readyState ==4){
if(request.status == 200){
var data = request.responseText.trim();
//가져온 데이터 가공
var rowdatas = data.split('\n');
var result = '';
for(var i =0; i<rowdatas.length; i++){
var coldatas = rowdatas[i].split(',');
result += '<ul>';
result += ' <li class="zipcode">'+coldatas[1]+'</li>';
result += ' <li class="sido">'+coldatas[2]+'</li>';
result += ' <li class="gugun">'+coldatas[3]+'</li>';
result += ' <li class="dong">'+coldatas[4]+'</li>';
result += ' <li class="ri">'+coldatas[5]+'</li>';
result += ' <li class="bunji">'+coldatas[6]+'</li>';
result += '</ul>';
}
document.getElementById('result').innerHTML = '';
document.getElementById('result').innerHTML = result;
}
}
};
//입력값 2자이상일때 ajax요청
if(document.getElementById('dong').value.trim().length >=2){
var strDong = encodeURI(document.getElementById('dong').value);
request.open('GET','./data/data.jsp?strDong='+strDong, true);
request.send();
}else{
alert('검색어를 2자 이상 입력하셔야 합니다.');
}
};
};
</script>
</head>
<body>
<label>동이름 입력</label> : <input type='text' id='dong' size='95' maxlength="20"/>
<button id='btn'>우편번호 검색</button>
<br>
<br>
<div>
<ul>
<li class ="header zipcode">번호</li>
<li class ="header sido">시도</li>
<li class ="header gugun">구군</li>
<li class ="header dong">동</li>
<li class ="header ri">리</li>
<li class ="header bunji">번지</li>
</ul>
</div>
<div id = 'result'></div>
</body>
</html>
2.XML DOM
xml트리구조를 통해 데이터를 추출 할 수 있음
3.xml파일 ajax요청
폴더구성
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = function(){
document.getElementById('btn').onclick = function(){
//xml데이터 처리
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState ==4){
if(request.status == 200){
//텍스트로 가져옴 //console.log(request.responseText);
//XML객체로 가져옴
console.log(request.responseXML);
}
}
};
request.open('GET', './data/data.xml', true);
request.send();
};
};
</script>
</head>
<body>
<button id="btn">비동기 요청</button>
<hr />
<div id="result"></div>
</body>
</html>
4.xml데이터 처리
ex.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = function(){
document.getElementById('btn').onclick = function(){
//xml데이터 처리
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState ==4){
if(request.status == 200){
//XML객체로 가져옴
var data = request.responseXML;
//직접 정보가져올 태그로 접근
var names = data.getElementsByTagName('name'); //같은 태그는 배열로 가져옴
var publishers = data.getElementsByTagName('publisher');
for(var i=0;i<names.length; i++){
var name = names[i].childNodes[0].nodeValue; //태그안의 텍스트는 자식노드임
var publisher = publishers[i].childNodes[0].nodeValue;
console.log(name+' / '+publisher);
}
}
}
};
request.open('GET', './data/data.xml', true);
request.send();
};
};
</script>
</head>
<body>
<button id="btn">비동기 요청</button>
<hr />
<div id="result"></div>
</body>
</html>
data.xml
<?xml version="1.0" encoding="utf-8"?>
<books>
<book>
<name>모던 웹 디자인을 위한 HTML +CSS3 입문</name>
<publisher>한빛미디어</publisher>
<author>윤인성</author>
<price>30000원</price>
</book>
<book>
<name>모던 웹 디자인을 위한 JavaScript + jQuery 입문</name>
<publisher>한빛미디어</publisher>
<author>윤인성</author>
<price>32000원</price>
</book>
<book>
<name>모던 웹 디자인을 위한 node.js 프로그래밍</name>
<publisher>한빛미디어</publisher>
<author>윤인성</author>
<price>22000원</price>
</book>
<book>
<name>모던 웹 디자인을 위한 HTML5 프로그래밍</name>
<publisher>한빛미디어</publisher>
<author>윤인성</author>
<price>30000원</price>
</book>
</books>
5.xml데이터 처리
ex.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = function(){
document.getElementById('btn').onclick = function(){
//xml데이터 처리
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState ==4){
if(request.status == 200){
//XML객체로 가져옴
var data = request.responseXML;
var books = data.getElementsByTagName('book'); //같은 태그는 배열로 가져옴
for(var i=0;i<books.length; i++){
//자식노드 배열을 숫자로 가져올경우 태그사이에 공간이 있으면 헷갈림
var name = books[i].childNodes[0].childNodes[0].nodeValue;
var publisher = books[i].childNodes[1].childNodes[0].nodeValue;
console.log(name+' / '+publisher);
}
}
}
};
request.open('GET', './data/data.xml', true);
request.send();
};
};
</script>
</head>
<body>
<button id="btn">비동기 요청</button>
<hr />
<div id="result"></div>
</body>
</html>
data.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- 한줄로 만듦 -->
<books>
<book><name>모던 웹 디자인을 위한 HTML +CSS3 입문</name><publisher>한빛미디어</publisher><author>윤인성</author><price>30000원</price></book>
<book><name>모던 웹 디자인을 위한 JavaScript + jQuery 입문</name><publisher>한빛미디어</publisher><author>윤인성</author><price>32000원</price></book>
<book><name>모던 웹 디자인을 위한 node.js 프로그래밍</name><publisher>한빛미디어</publisher><author>윤인성</author><price>22000원</price></book>
<book><name>모던 웹 디자인을 위한 HTML5 프로그래밍</name><publisher>한빛미디어</publisher><author>윤인성</author><price>30000원</price></book>
</books>
6. xml데이터 엔터키 탭키 있는경우 처리
data.xml
<?xml version="1.0" encoding="utf-8"?>
<books>
<book>
<name>모던 웹 디자인을 위한 HTML +CSS3 입문</name>
<publisher>한빛미디어</publisher>
<author>윤인성</author>
<price>30000원</price>
</book>
<book>
<name>모던 웹 디자인을 위한 JavaScript + jQuery 입문</name>
<publisher>한빛미디어</publisher>
<author>윤인성</author>
<price>32000원</price>
</book>
<book>
<name>모던 웹 디자인을 위한 node.js 프로그래밍</name>
<publisher>한빛미디어</publisher>
<author>윤인성</author>
<price>22000원</price>
</book>
<book>
<name>모던 웹 디자인을 위한 HTML5 프로그래밍</name>
<publisher>한빛미디어</publisher>
<author>윤인성</author>
<price>30000원</price>
</book>
</books>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = function(){
document.getElementById('btn').onclick = function(){
//xml데이터 처리
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState ==4){
if(request.status == 200){
//XML객체로 가져옴
var data = request.responseXML;
var books = data.getElementsByTagName('book'); //같은 태그는 배열로 가져옴
for(var i=0;i<books.length; i++){
//자식노드 태그사이 공백 있을경우 nodeType 검사 (element node =1)
for(var j=0; j<books[i].childNodes.length; j++){
if(books[i].childNodes[j].nodeType ==1){
var name = books[i].childNodes[j].childNodes[0].nodeValue;
console.log(name);
}
}
}
}
}
};
request.open('GET', './data/data.xml', true);
request.send();
};
};
</script>
</head>
<body>
<button id="btn">비동기 요청</button>
<hr />
<div id="result"></div>
</body>
</html>
7.json 요청데이터 처리
ex.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = function(){
document.getElementById('btn').onclick = function(){
//JSON데이터 처리
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState ==4){
if(request.status == 200){
//JSON은 텍스트로 받음
var data = request.responseText.trim();
//객체화
var json = eval('('+data+')');
var json = JSON.parse(data); //위와 동일한 결과
//JSON은 객체라서 처리가 간단함
for(var i=0;i<json.length; i++){
console.log(json[i].name);
}
}
}
};
request.open('GET', './data/data.json', true);
request.send();
};
};
</script>
</head>
<body>
<button id="btn">비동기 요청</button>
<hr />
<div id="result"></div>
</body>
</html>
data.json
[
{
"name": "모던 웹 디자인을 위한 HTML +CSS3 입문",
"publisher": "한빛미디어",
"author": "윤인성",
"price": "30000원"
},
{
"name": "모던 웹 디자인을 위한 JavaScript + jQuery 입문",
"publisher": "한빛미디어",
"author": "윤인성",
"price": "32000원"
},
{
"name": "모던 웹 디자인을 위한 node.js 프로그래밍",
"publisher": "한빛미디어",
"author": "윤인성",
"price": "22000원"
},
{
"name": "모모던 웹 디자인을 위한 HTML5 프로그래밍",
"publisher": "한빛미디어",
"author": "윤인성",
"price": "30000원"
}
]
8. json 파일 주소 검색
context.xml
<?xml version= "1.0" encoding="utf-8" ?>
<Context>
<Resource
name="jdbc/oracle"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:orcl"
username="scott"
password="tiger"
maxTotal="20"
maxWaitMillis="5000" />
</Context>
data_json.jsp
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true" %>
<%@ page import="model1.ZipTO"%>
<%@ page import="model1.ZipDAO"%>
<%@ page import="java.util.ArrayList"%>
<%
request.setCharacterEncoding("utf-8");
String strDong = "신사";
if(request.getParameter("strDong") != null) {
strDong = request.getParameter("strDong");
}
StringBuffer result = new StringBuffer();
ZipDAO dao = new ZipDAO();
ArrayList<ZipTO> ziplist = dao.zipList(strDong);
result.append("[");
for(int i=0 ; i<ziplist.size() ; i++) {
ZipTO to = ziplist.get(i);
String seq = to.getSeq();
String zipcode = to.getZipcode();
String sido = to.getSido();
String gugun = to.getGugun();
String dong = to.getDong();
String ri = to.getRi();
String bunji = to.getBunji();
//콤마 변수를 만들어서 문장 끝에는 포함하지 않음
String comma = (i==ziplist.size()-1)?"":",";
result.append("{");
result.append("\"seq\" : \""+ seq + "\",");
result.append("\"zipcode\" : \""+ zipcode + "\",");
result.append("\"sido\" : \""+ sido + "\",");
result.append("\"gugun\" : \""+ gugun + "\",");
result.append("\"dong\" : \""+ dong + "\",");
result.append("\"ri\" : \""+ ri + "\",");
result.append("\"bunji\" : \""+ bunji + "\"");
result.append("}");
result.append(comma);
}
result.append("]");
%>
<%=result %>
ZipSearch_json
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
ul {list-style-type: none; overflow: hidden; margin: 0px; padding: 0px;}
li {border:1px solid #000000; float: left; padding: 5px;}
.header {background-color: #99ff99; text-align: center;}
.zipcode, .sido, .gugun, .dong, .ri, .bunji {
width: 100px;
height: 20px;
text-align: center;
}
.ri, .bunji { width: 200px;}
</style>
<script>
window.onload =function(){
document.getElementById('btn').onclick = function(){
//Ajax객체 생성
var request = new XMLHttpRequest();
//요청 상태변화를 확인하고 응답텍스트를 출력
request.onreadystatechange = function(){
if(request.readyState ==4){
if(request.status == 200){
var data = request.responseText.trim();
//json 데이터 객체화
var json = JSON.parse(data);
var result = '';
for(var i =0; i<json.length; i++){
result += '<ul>';
result += ' <li class="zipcode">'+json[i].zipcode+'</li>';
result += ' <li class="sido">'+json[i].sido+'</li>';
result += ' <li class="gugun">'+json[i].gugun+'</li>';
result += ' <li class="dong">'+json[i].dong+'</li>';
result += ' <li class="ri">'+json[i].ri+'</li>';
result += ' <li class="bunji">'+json[i].bunji+'</li>';
result += '</ul>';
}
document.getElementById('result').innerHTML = '';
document.getElementById('result').innerHTML = result;
}
}
};
//입력값 2자이상일때 ajax요청
if(document.getElementById('dong').value.trim().length >=2){
var strDong = encodeURI(document.getElementById('dong').value);
request.open('GET','./data/data_json.jsp?strDong='+strDong, true);
request.send();
}else{
alert('검색어를 2자 이상 입력하셔야 합니다.');
}
};
};
</script>
</head>
<body>
<label>동이름 입력</label> : <input type='text' id='dong' size='95' maxlength="20"/>
<button id='btn'>우편번호 검색</button>
<br>
<br>
<div>
<ul>
<li class ="header zipcode">번호</li>
<li class ="header sido">시도</li>
<li class ="header gugun">구군</li>
<li class ="header dong">동</li>
<li class ="header ri">리</li>
<li class ="header bunji">번지</li>
</ul>
</div>
<div id = 'result'></div>
</body>
</html>
9. 주소검색후 테이블을 클릭하면 해당 동 주민센터 지도띄움
폴더 구성
context.xml
<?xml version= "1.0" encoding="utf-8" ?>
<Context>
<Resource
name="jdbc/oracle"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:orcl"
username="scott"
password="tiger"
maxTotal="20"
maxWaitMillis="5000" />
</Context>
ZipTO
package model1;
public class ZipTO {
private String seq;
private String zipcode;
private String sido;
private String gugun;
private String dong;
private String ri;
private String bunji;
public String getSeq() {
return seq;
}
public void setSeq(String seq) {
this.seq = seq;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getSido() {
return sido;
}
public void setSido(String sido) {
this.sido = sido;
}
public String getGugun() {
return gugun;
}
public void setGugun(String gugun) {
this.gugun = gugun;
}
public String getDong() {
return dong;
}
public void setDong(String dong) {
this.dong = dong ;
}
public String getRi() {
return ri;
}
public void setRi(String ri) {
this.ri = ri;
}
public String getBunji() {
return bunji;
}
public void setBunji(String bunji) {
this.bunji = bunji;
}
}
ZipDAO
package model1;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class ZipDAO {
private DataSource dataSource;
public ZipDAO() {
try {
Context initCtx = new InitialContext();
Context envCtx = (Context)initCtx.lookup("java:comp/env");
dataSource = (DataSource)envCtx.lookup("jdbc/oracle");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ArrayList<ZipTO> zipList(String dong) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList<ZipTO> zipLists = new ArrayList<>();
try {
conn = dataSource.getConnection();
String sql = "select seq, zipcode, sido, gugun, dong, ri, bunji from zipcode where dong like ? order by seq";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, dong + "%");
rs = pstmt.executeQuery();
while(rs.next()) {
ZipTO to = new ZipTO();
to.setSeq(rs.getString("seq"));
to.setZipcode(rs.getString("zipcode"));
to.setSido(rs.getString("sido"));
to.setGugun(rs.getString("gugun"));
to.setDong(rs.getString("dong"));
to.setRi(rs.getString("ri") == null ? "" : rs.getString("ri"));
to.setBunji(rs.getString("bunji") == null ? "" : rs.getString("bunji"));
zipLists.add(to);
}
} catch(SQLException e) {
System.out.println(e.getMessage());
} finally {
if(rs != null) try { rs.close(); } catch(SQLException e ) {}
if(pstmt != null) try { pstmt.close(); } catch(SQLException e) {}
if(conn != null) try { conn.close(); } catch(SQLException e) {}
}
return zipLists;
}
}
data_json.jsp
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true" %>
<%@ page import="model1.ZipTO"%>
<%@ page import="model1.ZipDAO"%>
<%@ page import="java.util.ArrayList"%>
<%
request.setCharacterEncoding("utf-8");
String strDong = "신사";
if(request.getParameter("strDong") != null) {
strDong = request.getParameter("strDong");
}
StringBuffer result = new StringBuffer();
//데이터 처리
ZipDAO dao = new ZipDAO();
ArrayList<ZipTO> ziplist = dao.zipList(strDong);
//json식으로 문장만듦
result.append("[");
for(int i=0 ; i<ziplist.size() ; i++) {
ZipTO to = ziplist.get(i);
String seq = to.getSeq();
String zipcode = to.getZipcode();
String sido = to.getSido();
String gugun = to.getGugun();
String dong = to.getDong();
String ri = to.getRi();
String bunji = to.getBunji();
//콤마 변수를 만들어서 문장 끝에는 포함하지 않음
String comma = (i==ziplist.size()-1)?"":",";
result.append("{");
result.append("\"seq\" : \""+ seq + "\",");
result.append("\"zipcode\" : \""+ zipcode + "\",");
result.append("\"sido\" : \""+ sido + "\",");
result.append("\"gugun\" : \""+ gugun + "\",");
result.append("\"dong\" : \""+ dong + "\",");
result.append("\"ri\" : \""+ ri + "\",");
result.append("\"bunji\" : \""+ bunji + "\"");
result.append("}");
result.append(comma);
}
result.append("]");
%>
<%=result %>
ZipSearchMap.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- 구글 지도 자바스크립트 라이브러리 가져옴 -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=####자신의 키#####&sensor=false"></script>
<!-- jQuery 라이브러리 가져옴 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
<style>
ul {list-style-type: none; overflow: hidden; margin: 0px; padding: 0px;}
li {border:1px solid #000000; float: left; padding: 5px;}
.header {background-color: #99ff99; text-align: center;}
.zipcode, .sido, .gugun, .dong, .ri, .bunji {
width: 100px;
height: 20px;
text-align: center;
}
.ri, .bunji { width: 200px;}
</style>
<script>
window.onload =function(){
document.getElementById('btn').onclick = function(){
//Ajax객체 생성
var request = new XMLHttpRequest();
//입력값 2자이상일때 ajax요청
if(document.getElementById('dong').value.trim().length >=2){
var strDong = encodeURI(document.getElementById('dong').value);
request.open('GET','./data/data_json.jsp?strDong='+strDong, true);
request.send();
}else{
alert('검색어를 2자 이상 입력하셔야 합니다.');
}
//응답처리
request.onreadystatechange = function(){
if(request.readyState ==4){
if(request.status == 200){
var data = request.responseText.trim();
//json 데이터 객체화
var json = JSON.parse(data);
var result = '';
//데이터 출력
for(var i =0; i<json.length; i++){
result += '<ul>';
result += ' <li class="zipcode">'+json[i].zipcode+'</li>';
result += ' <li class="sido">'+json[i].sido+'</li>';
result += ' <li class="gugun">'+json[i].gugun+'</li>';
result += ' <li class="dong">'+json[i].dong+'</li>';
result += ' <li class="ri">'+json[i].ri+'</li>';
result += ' <li class="bunji">'+json[i].bunji+'</li>';
result += '</ul>';
}
document.getElementById('result').innerHTML = result;
//맵이 띄워져있으면 지움
$('#map').empty().height(0);
}
}
};
};
//가져온 zipcode주소 클릭시 주민센터 지도 띄움
$(document).on('click','ul', function(){
//클릭한 동 인코딩
var dong = $(this).find('.dong').html();
var address = encodeURIComponent(dong);
//Ajax객체 생성
var request = new XMLHttpRequest();
//구글지도 json요청
request.open('GET','https://maps.googleapis.com/maps/api/geocode/json?address='+address, true);
request.send();
//응답 처리
request.onreadystatechange = function(){
if(request.readyState ==4){
if(request.status == 200){
var data = request.responseText.trim();
//json 데이터 객체화
var json = JSON.parse(data);
//위도 경도 가져오기
var lat = json.results[0].geometry.location.lat;
var lng = json.results[0].geometry.location.lng;
//맵표시할 태그 객체 선택
var mapShow = $('#map').height(300);
var element = mapShow.get(0);
//맵 표시
var map = new google.maps.Map(element,{
zoom: 14,
center: new google.maps.LatLng(lat,lng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//위치 표시
new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
title: dong+'주민센터'
});
}
}
};
});
};
</script>
</head>
<body>
<label>동이름 입력</label> : <input type='text' id='dong' size='95' maxlength="20"/>
<button id='btn'>우편번호 검색</button>
<br>
<br>
<div id='map'></div>
<div>
<ul>
<li class ="header zipcode">번호</li>
<li class ="header sido">시도</li>
<li class ="header gugun">구군</li>
<li class ="header dong">동</li>
<li class ="header ri">리</li>
<li class ="header bunji">번지</li>
</ul>
</div>
<div id='result'></div>
</body>
</html>
댓글 없음:
댓글 쓰기