xml openApi bookSearch Ex

메타플랫폼대표
|2024. 7. 8. 16:40
반응형

Xml 작업파일(XmlTest)

 

GitHub - chaSunil/FirstProject: 1차 프로젝트

1차 프로젝트. Contribute to chaSunil/FirstProject development by creating an account on GitHub.

github.com

 

<!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: 1000px;
		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_name").val("");
			$("#b_name").focus();
			return;
		}
		// 가져올 시작 상품위치(p_page에 2를 넣으면 11번부터 시작)
		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 xml.vo;

public class BookVo {

	int no;
	
	String title;
	String link;
	String image;
	String author;
	
	int discount;
	String publisher;
	int pubdate;
	String description;
	
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getLink() {
		return link;
	}
	public void setLink(String link) {
		this.link = link;
	}
	public String getImage() {
		return image;
	}
	public void setImage(String image) {
		this.image = image;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public int getDiscount() {
		return discount;
	}
	public void setDiscount(int discount) {
		this.discount = discount;
	}
	public String getPublisher() {
		return publisher;
	}
	public void setPublisher(String publisher) {
		this.publisher = publisher;
	}
	public int getPubdate() {
		return pubdate;
	}
	public void setPubdate(int pubdate) {
		this.pubdate = pubdate;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	
	
	
}
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;

public class MySearchUtilBook {
	// 객체 생성 없이 바로 사용 가능
	public static List<BookVo> search_shop(String b_name,int start,int display)
	{
		List<BookVo> list = new ArrayList<BookVo>();
		String clientId = "HSnvoxqFuNlT20cUc6Bv";
		String clientSecret = "2XBVa64aOh";

		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 = (List<Element>)root.getChild("channel").getChildren("item");

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

			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
		return list;
	}
	
	
}
package action;

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

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;

/**
 * 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;
		// alt + shift + z 사용해서 try/catch 사용
		try {
			start = Integer.parseInt(request.getParameter("start"));
			display = Integer.parseInt(request.getParameter("display"));
		} catch (Exception 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);

	}

}
<%@ 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>
		</tr>
		<!-- for(ProductVo vo : p_list -->
		<c:forEach var="vo" items="${ b_list }" varStatus="i">
			<tr>
				<td>${ vo.no }</td>
				<td><img src="${ vo.image }"></td>
				<td>${ vo.author }</td>
				<td><a href="${ vo.link }">${ vo.title }</a></td>
				<td><fmt:formatNumber type="currency" value="${ vo.discount }"/></td>
				<td>${ vo.publisher }</td>
				<td>${ vo.pubdate }</td>
				<td>${ vo.description }</td>
			</tr>
		</c:forEach>
		
	</table>


</body>
</html>

반응형

'데이터베이스↗' 카테고리의 다른 글

json kakao open api 활용하기  (0) 2024.07.09
json Data 활용  (0) 2024.07.09
xml openApi 이용하기  (0) 2024.07.08
xml로 데이터를 가져와서 parsing까지 하기  (0) 2024.07.08
JDBC 방명록 작성 (CRUD)  (0) 2024.06.20