xml

xml - 네이버API활용 예제(책)

우가본 2024. 7. 8. 16:34

도서 검색 util 메서드

package util;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import xml.vo.BookVo;
import xml.vo.ProductVo;

public class MySearchUtilBook {

	// 객체 생성없이 사용가능한 스태틱 메서드 활용
	// dao에서 싱글톤을 사용하는 것과 동일한 이치
	public static List<BookVo> search_shop(String b_name,int start,int display)
	{
		List<BookVo> list = new ArrayList<BookVo>();
		String clientId = "BljnawOS5mfzkwMuYC3P";
		String clientSecret = "VdkVKvKKDf";

		try {
			b_name = URLEncoder.encode(b_name, "utf-8");
			String urlStr = String.format("https://openapi.naver.com/v1/search/book.xml?query=%s&start=%d&display=%d",
					         b_name,start,display
					);

			URL url = new URL(urlStr);
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			//발급받은 ID
			connection.setRequestProperty("X-Naver-Client-Id", clientId); 
			//발급받은 PW
			connection.setRequestProperty("X-Naver-Client-Secret", clientSecret); 
			// 받을요청타입
			connection.setRequestProperty("Content-Type", "application/xml"); 
			connection.connect();

			SAXBuilder builder = new SAXBuilder();
			
			Document   doc = builder.build (connection.getInputStream());

			Element  root     = doc.getRootElement();
			List<Element>   item_list = root.getChild("channel").getChildren("item");

			int no = start;
			
			for(Element item : item_list){
				String title = item.getChildText("title");
				String link  = item.getChildText("link");
				String image = item.getChildText("image");
				String author = item.getChildText("author");
				int price=0,discount=0;
				try {
					price = Integer.parseInt(item.getChildText("price"));
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				try {
					discount = Integer.parseInt(item.getChildText("discount"));
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				String publisher = item.getChildText("publisher");
				String pubdate = item.getChildText("pubdate");
				String isbn = item.getChildText("isbn");
				
				//상품목록을 포장
				BookVo vo = new BookVo();
				vo.setNo(no++);
				vo.setTitle(title);
				vo.setLink(link);
				vo.setImage(image);
				vo.setAuthor(author);
				vo.setPrice(price);
				vo.setDiscount(discount);
				vo.setPublisher(publisher);
				vo.setPubdate(pubdate);
				vo.setIsbn(isbn);
							
				//ArrayList에 넣기
				list.add(vo);
				
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return list;
	}
	
}

 

)BookVo

 

)search_book.html (ajax 활용)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<style type="text/css">

	#box{
		width: 1300px;
		margin: auto;
		margin-top: 20px;
	}
	
</style>

<script type="text/javascript">
	function search(){
		
		let b_name = $("#b_name").val().trim();
		let page = $("#page").val();
		let display = $("#display").val();
		
		if(b_name==''){
			alert("도서명을 입력하세요");
			$("#b_nmae").val("");
			$("#b_name").focus();
			return;
		}
		
		// 가져올 시작 상품위치
		let start = (page-1) * display + 1;
		
		//Ajax이용해서 (상품)요청
		$.ajax({
			url		:	"book/list.do",	//BookListAction
			data	:	{"b_name":b_name, "start":start, "display":display},
			success	:	function(res_data){
				$("#disp").html(res_data);
			},
			error	:	function(err){
				alert(err.responseText);
			}
		});
	}
</script>
</head>
<body>
	<div id="box">
		<form class="form-inline">
			도서명: <input class="form-control" id="b_name">
				  <input class="btn btn-primary" type="button" value="검색" onclick="search();">
				  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
				  
			페이지: <select class="form-control" id="page">
				  	<option value="1">1</option>
				  	<option value="2">2</option>
				  	<option value="3">3</option>
				  	<option value="4">4</option>
				  	<option value="5">5</option>
				  </select>
				  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
			페이지당 조회수: 
				  <select class="form-control" id="display">
				  	<option value="10">10개씩 보기</option>
				  	<option value="20">20개씩 보기</option>
				  	<option value="30">30개씩 보기</option>
				  	<option value="50">50개씩 보기</option>
				  	<option value="100">100개씩 보기</option>
				  </select>
			<hr>
			<div id="disp"></div>
		</form>		
	</div>
</body>
</html>

 

)도서 목록 조회 서블릿

package action;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import util.MySearchUtil;
import util.MySearchUtilBook;
import xml.vo.BookVo;
import xml.vo.ProductVo;

import java.io.IOException;
import java.util.List;

/**
 * Servlet implementation class ProductListAction
 */
@WebServlet("/book/list.do")
public class BookListAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// /product/list.do?p_name=노트북&start=1&display=10
		
		request.setCharacterEncoding("utf-8");
		String b_name = request.getParameter("b_name");
		
		int	start   = 1;
		int display = 10;
		
		try {
			start   = Integer.parseInt(request.getParameter("start"));
			display = Integer.parseInt(request.getParameter("display"));
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}
		
		// Naver Open API를 이용해서 상품검색...
		List<BookVo> b_list = MySearchUtilBook.search_shop(b_name, start, display);
		
		// request binding
		request.setAttribute("b_list", b_list);

		// Dispatcher형식으로 호출
		String forward_page = "book_list.jsp";
		RequestDispatcher disp = request.getRequestDispatcher(forward_page);
		disp.forward(request, response);

	}

}

 

)도서 목록 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" %>    

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<style type="text/css">
	img{
		width: 120px;
		height: 100px;
	}
	
	td{
		vertical-align: middle !important;
	}
</style>

</head>
<body>
	<table class="table">
		<tr class="success">
			<th>순번</th>
			<th>이미지</th>
			<th>상품명</th>
			<th>작가</th>
			<th>가격</th>
			<th>할인가</th>
			<th>출판사</th>
			<th>출판일자</th>
			<th>제품번호</th>
		</tr>
		<!-- for(ProductVo vo : p_list -->
		<c:forEach var="vo" items="${ b_list }" varStatus="i"> <!-- BookListAction -->
			<tr>
				<td>${ vo.no}</td>
				<td><img src="${ vo.image }"></td>
				<td><a href="${ vo.link }">${ vo.title }</a></td>
				<td>${ vo.author }</td>
				<td><fmt:formatNumber type="currency" value="${ vo.price }"/></td>
				<td><fmt:formatNumber type="currency" value="${ vo.discount }"/></td>
				<td>${ vo.publisher }</td>
				<td>${ vo.pubdate }</td>
				<td>${ vo.isbn }</td>
			</tr>
		</c:forEach>
	</table>
</body>
</html>