Eclipse package
(1) org.kh.api.controller
Servlet : SearchMovieServlet (영화 순위 검색)
package org.kh.api.controller;
import java.io.IOException;
import java.text.SimpleDateFormat;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jsoup.Jsoup;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* Servlet implementation class SearchMovieServlet
*/
@WebServlet(name = "SearchMovie", urlPatterns = { "/searchMovie" })
public class SearchMovieServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SearchMovieServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//요청 url
String url = "http://www.kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json";
//key값에 들어갈 발급받은 키값
String key = "2d1960a325f72e312330c46c40440bb2";
//targetDt 들어갈 날짜 포멧 생성
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//어제날짜로
String yesterday = sdf.format(System.currentTimeMillis()-86400000);
String result = Jsoup.connect(url) //매개변수 url 요청
.data("key",key)
.data("targetDt",yesterday)
.userAgent("Mozilla")
.ignoreContentType(true)
.execute().body();
System.out.println(result);
//String 타입 데이터를 변환하기위한 변환용 객체 생성
JsonParser parser = new JsonParser();
//result를 변환하여 JsonObject객체에 저장 -> 원래 변환하기 전 타입은 Object
JsonObject resultInfo = (JsonObject)parser.parse(result);
//키값이 boxOfficeResult 인 값을 저장
JsonObject detail1 = resultInfo.getAsJsonObject("boxOfficeResult");
//JsonArray 로 박스오피스 순위를 저장
JsonArray rank = detail1.getAsJsonArray("dailyBoxOfficeList");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
new Gson().toJson(rank, response.getWriter());
//여기서 넘기면 apiTest 의 무비에 있는 함수의 (data)가 jSon
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
(2) view
apitest.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="https://openapi.map.naver.com/openapi/v3/maps.js?ncpClientId=7geaqrnt5l&submodules=geocoder"></script>
<script type="text/javascript" src="https://cdn.iamport.kr/js/iamport.payment-1.1.5.js"></script>
<script type="text/javascript" src="https://t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js"></script>
</head>
<body>
<%@include file = "/WEB-INF/views/common/header.jsp" %>
<section>
<div class = "container" style ="color : black;">
<h2>1. 네이버 지도 API</h2>
<div id = "map" style="width:100%; height:500px;"></div>
<hr>
<h2>2. 결제 모듈 API</h2>
<br>
<div id = "pay">
<h4>
<label><input type="checkbox" value="1000">1000원</label>
<label><input type="checkbox" value="5000">5000원</label>
<label><input type="checkbox" value="10000">10000원</label>
<label><input type="checkbox" value="50000">50000원</label>
</h4>
<h3>
총 결제 금액
<span style="dispaly:inline-block; width:150px; text-align:right;"></span>
원
</h3>
<button class="btn btn-info">결제하기</button>
<p id="paymentResult"></p>
</div>
<hr>
<h2>3. 다음 주소찾기 API 사용</h2>
<ul>
<li>
<input id='postCode' style="width:200px; display:inline-block" type="text" class="form-control" readonly>
<button id="addrSearchBtn" onclick="addrSearch();" class="btn btn-info">주소검색</button>
</li>
<li>
<input id='roadAddr' style="width:400px; display:inline-block" type="text" class="form-control" readonly>
<input id='jibunAddr' style="width:400px; display:inline-block" type="text" class="form-control" readonly>
</li>
<li>
<input id='detailAddr' style="width:500px; display:inline-block" type="text" class="form-control">
</li>
</ul>
<h2>4. 영화 박스 오피스 </h2>
<div id = 'movieList'>
<button id = 'movieBtn' class="btn btn-primary">순위확인</button>
<div id="movieResult"></div>
</div>
</div>
</section>
<script>
//4. 박스오피스 순위
$("#movieBtn").click(function(){
$.ajax({
url : "/searchMovie",
type : "get",
success : function(data){
for(var index in data){
$("#movieResult").append("<hr>");
$("#movieResult").append("순위 : " + data[index].rank+"<br>");
$("#movieResult").append("영화제목 : " + data[index].movieNm+"<br>");
}
},
error : function(){
console.log("실패");
}
});
});
//3. 다음 주소찾기 연동
function addrSearch(){
new daum.Postcode({
oncomplete:function(data){
$("#postCode").val(data.zonecode);
$("#roadAddr").val(data.roadAddress);
$("#jibunAddr").val(data.jibunAddress)
}
}).open();
}
//2. 결제모듈 연동
$(document).ready(function(){
var totalPay=0;
$("#pay input").change(function(){
if($(this).is(":checked")){
totalPay += (Number)($(this).val());
}else{
totalPay -= (Number)($(this).val());
}
$("#pay span").html(totalPay);
});
$("#pay button").click(function(){
var price = $("#pay span").html();
//상품명_현재시간
var d = new Date();
var date = d.getFullYear()+''+(d.getMonth()+1)+''+d.getDate()+''+d.getHours()+''+d.getMinutes()+''+d.getSeconds();
IMP.init('imp31083748'); // 결제 API를 사용하기 위한 코드 입력!
IMP.request_pay({ //결제 요청
merchant_uid : '상품명_' + date, //상점 거래 ID
name : '결제테스트', // 결제 명
amount : price, // 결제금액
buyer_email : 'xxxxxxx@naver.com', // 구매자 email
buyer_name : '구매자', // 구매자 이름
buyer_tel : '010-1234-4567', // 구매자 전화번호
buyer_addr : '서울특별시 영등포구', // 구매자 주소
buyer_postcode : '123-456' // 구매자 우편번호
}, function(rsp){
if(rsp.success){
var msg = '결제가 완료 되었습니다.';
var r1 = '고유 아이디 : ' +rsp.imp_uid;
var r2 = '상점 거래 아이디 : ' +rsp.merchant_uid;
var r3 = '결제 금액 : ' +rsp.paid_amount;
var r4 = '카드 승인 번호 : '+rsp.apply_num;
alert(msg);
$("#paymentResult").html(r1+"<br>"+r2+"<br>"+r3+"<br>"+r4);
}else{
$("#paymentResult").html('결제실패<br>'+'에러내용 : ' +rsp.error_msg);
}
});
});
});
//1. 네이버 지도 api 사용
window.onload=function(){
var map = new naver.maps.Map('map',{
center : new naver.maps.LatLng(37.533807,126.896772),
zoom : 10,
zoomControl : true,
zoomControlOptions:{
position : naver.maps.Position.TOP_RIGHT,
style : naver.maps.ZoomControlStyle.SMALL
}
});
var marker = new naver.maps.Marker({
position : new naver.maps.LatLng(37.533807,126.896772),
map:map
});
naver.maps.Event.addListener(map,'click',function(e){ //맵에 클릭 이벤트 발생시!
marker.setPosition(e.coord);
if(infoWindow != null){ //
if(infoWindow.getMap()){ //열러있는지 안열려있는지 판단
infoWindow.close();
}
}
//위, 경도를 이용하여 주소를 얻어오기 위해서는 reverseGeocode 를 사용해야함
//클라이언트 키 뒤에 &submodules=geocoder 를 추가 (추가해야 사용가능)
naver.maps.Service.reverseGeocode({
location : new naver.maps.LatLng(e.coord.lat(),e.coord.lng())
},function(status,response){
if(status !== naver.maps.Service.Status.OK){
return alert("실패");
}
var result = response.result,
items = result.items; // 배열 타입으로 응답을 받아서 변수에 저장
address = items[2].address; // 0-> 지번주소, 1-> 도로명 2->
contentString = [
'<div class="iw_inner">',
' <h3>KH정보교육원</h3>',
' <p>'+address+'</p>',
'</div>'
].join('');
});
});
var contentString = [
'<div class="iw_inner">',
' <h3>KH정보교육원</h3>',
' <p>서울특별시 영등포구 선유동2로 57 이레빌딩 19F, 20F</p>',
'</div>'
].join('');
var infoWindow = new naver.maps.InfoWindow();
naver.maps.Event.addListener(marker,'click',function(e){
if(infoWindow.getMap()){ //윈도우창 열고 다른곳 찍었을때 닫히는것
infoWindow.close();
}else{
infoWindow = new naver.maps.InfoWindow({
content : contentString
});
infoWindow.open(map,marker);
}
});
}
</script>
</body>
</html>
1. 네이버 지도 API
2. 결제 모듈 API
3. 다음 주소찾기 API 사용
4. 영화 박스 오피스
'이공계전문기술연수 > Servlet | JSP' 카테고리의 다른 글
<이공계기술전문연수> 15. Servlet / JSP Ajax 실습 (0) | 2019.11.22 |
---|---|
<이공계기술전문연수> 14. Servlet / JSP MVC2 실습(6) 사진등록(ajax) (0) | 2019.11.21 |
<이공계기술전문연수> 13. Servlet / JSP MVC2 실습(5) 공지사항 (0) | 2019.11.21 |
<이공계기술전문연수> 12. Servlet / JSP MVC2 실습(4) 아이디찾기 / 비밀번호찾기 / 아이디 중복체크 (2) | 2019.11.20 |
<이공계기술전문연수> 11. Servlet / JSP MVC2 실습(3) 회원정보 수정/회원 탈퇴/마이 페이지 / 회원 전체 관리 / 회원 정보 검색 (0) | 2019.11.20 |