본문 바로가기

spring/소스코드

카카오API데이터를 DB Table에 입력저장하기

DaumController.java(class)


package com.example.web;

import java.util.HashMap;

import javax.inject.Inject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.domain.Criteria;
import com.example.domain.LocalVO;
import com.example.domain.PageMaker;
import com.example.persistence.LocalDAO;

@Controller
public class DaumController {
	@Inject
	LocalDAO dao;
	
	//daum.jsp이동
	@RequestMapping("daum")
	public String daum(){
		return "daum";
	}
	//입력
	@ResponseBody
	@RequestMapping("insert")
	public void insert(LocalVO vo) throws Exception{
		dao.insert(vo);
	}
	@ResponseBody
	@RequestMapping("local.json")
	public HashMap<String, Object> list(Criteria cri)throws Exception{
		cri.setPerPageNum(5);
		HashMap<String, Object> map=new HashMap<String, Object>();
		map.put("list", dao.list(cri));
		
		PageMaker pm=new PageMaker();		
		pm.setCri(cri);
		pm.setTotalCount(dao.total());
		map.put("pm", pm);
		
		return map;
	}
	@ResponseBody
	@RequestMapping(value="delete",method=RequestMethod.POST)
	public void delete(int id) throws Exception{
		//LocalVO vo=new LocalVO();
		//System.out.println(vo.toString());
		dao.delete(id);
	}
	@ResponseBody
	@RequestMapping(value="update",method=RequestMethod.POST)
	public void update(LocalVO vo) throws Exception{
		System.out.println(vo.toString());
		dao.update(vo);
	}
}


daum.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>


	다음 지역 검색[다음 지역 검색]          검색:   건
	{{#each documents}}
	<tr class="row">
		<td><input type="checkbox"></td>
		<td class="place_name">{{place_name}}</td>
		<td class="address_name">{{address_name}}</td>
		<td class="phone">{{phone}}</td>
		<td><button x="{{x}}" y="{{y}}" phone="{{phone}}" place_name="{{place_name}}">지도보기</button></td>
	</tr>
	{{/each}}
	◀◁ ▶▷
닫기
	//전역변수
		var page=1;
		var query=$("#query").val();
	//선택저장
		$("#btnInsert").on("click", function(){
			if(!confirm("저장하시겠습니까?")) return;
			//체크박스가 checked 되어있는것만 반복해서 가져옴.
			$("#tbl tr input:checkbox:checked").each(function(){
				var row=$(this).parent().parent();
				var place_name=row.find(".place_name").html();
				//alert(place_name);
				var address_name=row.find(".address_name").html();
				var phone=row.find(".phone").html();
				
				$.ajax({
					type:"get",
					url:"insert",
					data:{"place":place_name,"address":address_name,"phone":phone},
					success:function(){					
					}
					
				});
				//checkbox 선택된거 해제
				$(this).prop("checked", false);
			});
			alert("저장되었습니다.");
			getLocal();
			//chkall checkbox 해제
			$("#chkAll").prop("checked",false);
		});
	
	
	
	
	/*
	//checkbox를 누르면 table에 checkbox가 모두 선택됨 
		$("#chkAll").on("click", function(){
			//선택저장 checkbox가 checked 되어있으면
			if($(this).is(":checked")){
				$("#tbl tr input:checkbox").each(function(){
					$(this).prop("checked", true);
					//checkbox 모두 체크
				});
			}else{
				$("#tbl tr input:checkbox").each(function(){
					$(this).prop("checked", false);
				});
			}
		});
	*/
		
	
	
	$("#chkAll").on("click" ,function(){
		if($(this).is(":checked")){
			$("#tbl tr input:checkbox").on("click", function(){
				$("#chkAll").prop("checked",false);
			});	
			$("#tbl tr input:checkbox").each(function(){
				$(this).prop("checked", true);
				//checkbox 모두 체크
			});
		}else{
			$("#tbl tr input:checkbox").each(function(){
				$(this).prop("checked", false);
			});
		}
	});
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	//검색프로그램
		$("#btnSearch").on("click", function(){
			page=1;
			query=$("#query").val();
			getList();
			$("#chkAll").prop("checked",false);
		});
	//lightbox 실행
		$("#tbl").on("click", "tr button", function(){
			$("#darken").show();
			var lat=$(this).attr("y");
			var lng=$(this).attr("x");
			var phone=$(this).attr("phone");
			var place_name=$(this).attr("place_name");
			var container = document.getElementById('map'); //지도를 담을 영역의 DOM 레퍼런스
		//id가 map인 곳에 출력하겠다.
			var options = { //지도를 생성할 때 필요한 기본 옵션
				center: new kakao.maps.LatLng(lat,lng), //지도의 중심좌표.
				level: 3 //지도의 레벨(확대, 축소 정도)
			};
			var map = new kakao.maps.Map(container, options); //지도 생성 및 객체 리턴
		//marker 생성
			var marker=new kakao.maps.Marker({
				position:new kakao.maps.LatLng(lat,lng)
			})
		//marker를 map에 set하기
			marker.setMap(map);		
		//marker에 정보 출력하기
			var info=new kakao.maps.InfoWindow({
				content:"<center><b>전화:" + phone + "</b></center>"
						+ "<center><b>장소:" + place_name + "</b></center>"
			})
			kakao.maps.event.addListener(marker, "mouseover", function(){
				info.open(map, marker);
			})
			kakao.maps.event.addListener(marker, "mouseout", function(){
			info.close(map, marker);
			})
		});
	//라이트박스 닫기
		$("#btnClose").on("click",function(){
			$("#darken").hide();
		});
	//검색프로그램
		$("#query").keydown(function(key){
			page=1;
			if(key.keyCode==13){
				query=$("#query").val();
				getList();
				$("#chkAll").prop("checked",false);
			}
		});
	//페이지 이동
		$("#btnNext").on("click", function(){			
			//마지막페이지가 아니면
			if(!is_end){
				page += 1;
				getList();	
			}			
		});
		$("#btnPre").on("click", function(){
			if(page > 1){
				page -= 1;
				getList();
			}
		});
	//json데이터 출력
		getList();
		function getList(){
			$.ajax({
				type:"get",
				url:"https://dapi.kakao.com/v2/local/search/keyword.json",
				headers:{"Authorization":"KakaoAK 6baa3500ff42695b48d705aa87132cb3"},
				dataType:"json",
				data:{"query":query,"size":"5","page":page},
				success:function(data){
					var temp=Handlebars.compile($("#temp").html());
					$("#tbl").html(temp(data));
					$("#total").html(data.meta.total_count);
				//end값을 받아와야 end값을 계산할 수 있다.
					is_end=data.meta.is_end;
				}				
			});
		}
	

LocalVO.java(class)

 

package com.example.domain;

public class LocalVO {
	private int id;
	private String place;
	private String address;
	private String phone;
	
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getPlace() {
		return place;
	}
	public void setPlace(String place) {
		this.place = place;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	
	
	@Override
	public String toString() {
		return "LocalVO [id=" + id + ", place=" + place + ", address=" + address + ", phone=" + phone + "]";
	}
	
	
	
}

Criteria.java(class)

package com.example.domain;
public class Criteria{
	  private int page;
	  private int perPageNum;
	  
	  public Criteria(){
	    this.page = 1;
	    this.perPageNum = 3;
	  }
	  
	  public void setPage(int page){
	    if (page <= 0){
	      this.page = 1;
	      return;
	    }
	    this.page = page;
	  }
	  public void setPerPageNum(int perPageNum){
	    if(perPageNum <= 0 || perPageNum > 100){
	      this.perPageNum = 10;
	      return;
	    }
	    this.perPageNum = perPageNum;
	  }
	  public int getPage(){
	    return page;
	  }
	  
	  public int getPageStart(){
	    return (this.page - 1) * perPageNum;
	  }
	 
	  public int getPerPageNum(){
	    return this.perPageNum;
	  }
	  @Override
	  public String toString(){
	    return "Criteria [page=" + page + ", " + "perPageNum=" + perPageNum + "]";
	  }
	}

 

PageMaker.java(class)

package com.example.domain;
public class PageMaker{
	  private int totalCount;
	  private int startPage;
	  private int endPage;
	  private boolean prev;
	  private boolean next;
	  private int displayPageNum = 10;
	  private Criteria cri;
	  
	  public void setCri(Criteria cri){
	    this.cri = cri;
	  }
	  public void setTotalCount(int totalCount){
	    this.totalCount = totalCount;
	    calcData();
	  }
	  private void calcData(){
	    endPage = (int) (Math.ceil(cri.getPage() / (double) displayPageNum) * displayPageNum);
	    startPage = (endPage - displayPageNum) + 1;
	    int tempEndPage = (int) (Math.ceil(totalCount / (double) cri.getPerPageNum()));
	    if(endPage > tempEndPage){
	      endPage = tempEndPage;
	    }
	    prev = startPage == 1 ? false : true;
	    next = endPage * cri.getPerPageNum() >= totalCount ? false : true;
	  }
	public int getStartPage() {
		return startPage;
	}
	public void setStartPage(int startPage) {
		this.startPage = startPage;
	}
	public int getEndPage() {
		return endPage;
	}
	public void setEndPage(int endPage) {
		this.endPage = endPage;
	}
	public boolean isPrev() {
		return prev;
	}
	public void setPrev(boolean prev) {
		this.prev = prev;
	}
	public boolean isNext() {
		return next;
	}
	public void setNext(boolean next) {
		this.next = next;
	}
	public int getDisplayPageNum() {
		return displayPageNum;
	}
	public void setDisplayPageNum(int displayPageNum) {
		this.displayPageNum = displayPageNum;
	}
	public int getTotalCount() {
		return totalCount;
	}
	public Criteria getCri() {
		return cri;
	}
}

 

 

LocalDAO.interface(interface)

 


package com.example.persistence;

import java.util.List;

import com.example.domain.Criteria;
import com.example.domain.LocalVO;

public interface LocalDAO {
	public List list(Criteria cri) throws Exception;
	public void insert(LocalVO vo) throws Exception;
	public int total() throws Exception;
	public void delete(int id) throws Exception;
	public void update(LocalVO vo) throws Exception;
}


LocalMapper.xml(xml)



		select * from local
		order by id desc
		limit #{pageStart},#{perPageNum}
	
	
		insert into local(place,address,phone) 
		values(#{place},#{address},#{phone})
		select count(*) from local
	
	
		delete from local 
		where id=#{id}
	
	
		update local 
		set address=#{address},phone=#{phone}
		where id=#{id}
	

 

LocalDAOImpl.java(class)

 


	package com.example.persistence;

import java.util.List;

import javax.inject.Inject;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;

import com.example.domain.Criteria;
import com.example.domain.LocalVO;

@Repository
public class LocalDAOImpl implements LocalDAO{
	@Inject
	SqlSession session;
	private static final String namespace="LocalMapper";
	@Override
	public void insert(LocalVO vo) throws Exception {
		session.insert(namespace +".insert",vo);
	}
	@Override
	public List list(Criteria cri) throws Exception {
		// TODO Auto-generated method stub
		return session.selectList(namespace +".list", cri);
	}
	@Override
	public int total() throws Exception {
		// TODO Auto-generated method stub
		return session.selectOne(namespace +".total");
	}
	@Override
	public void delete(int id) throws Exception {
		// TODO Auto-generated method stub
		session.delete(namespace +".delete",id);
	}
	@Override
	public void update(LocalVO vo) throws Exception {
		// TODO Auto-generated method stub
		session.update(namespace +".update",vo);
	}

}

		
		
	

Local.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>



	
	내 테이블에 있는 지역 데이터
	
	

                

                
                











                
                

	

[내 테이블에 있는 지역 데이터]