Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 |
Tags
- URL입력
- 프로젝트 후기
- 첫 React
- 웹 개발 면접 질문
- react
- e-HR
- 뷰
- 트리
- 간단 프로젝트
- 쟈스
- 백준알고리즘
- Vue.js
- 뷰 리액트
- 1차면접
- 리액트
- SBS 본사
- 사내시스템
- SBS 개발
- 뷰 리액트 비교
- MySQL
- 면접
- CompositionAPI
- 첫 리액트
- 오라클
- IT시스템개발
- 자바
- 대문자
- 알고리즘
- 경력직
- 백준
Archives
- Today
- Total
리주의 프로그래밍 공부
[Spring] ajax를 이용한 실시간 검색 출력 본문
네이버 도서 검색 API를 사용했습니다.
developers.naver.com/docs/search/book/
// 도서명과 페이지를 넘겨 받고, 한글이 깨지지 않기 위함
@GetMapping(value="/writing/search/{name}/{page}", produces = "text/plain; charset=UTF-8")
@ResponseBody // xml 출력을 위함
public String search(@PathVariable String name, @PathVariable int page) {
String clientID = "{어플리케이션 등록 후 확인}";
String clientSecret = "{어플리케이션 등록 후 확인}";
try {
// 검색어를 주소에 넣기 위한 인코딩
String text = URLEncoder.encode(name, "UTF-8");
// 세부검색(도서명 : d_titl)
String apiURL = "https://openapi.naver.com/v1/search/book_adv.xml?d_titl=" + text + "&start=" + ((page - 1) * 10 + 1);
URL url = new URL(apiURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("X-Naver-Client-Id", clientID);
con.setRequestProperty("X-Naver-Client-Secret", clientSecret); // get request
int responseCode = con.getResponseCode();
BufferedReader br;
if (responseCode == 200) {
System.out.println("정상 호출");
br = new BufferedReader(new InputStreamReader(con.getInputStream()));
} else {
System.out.println("호출 오류");
br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
return response.toString();
} catch (Exception e) {
System.out.println(e);
return "실패";
}
}
Controller
var page;
$(document).ready(function(){
searchbook();
});
function searchbook(){
// id가 book-name인 칸에 키가 눌렸을 때
$("#book-name").keyup(function(){
// 기존 검색 비워주기
$("#srch-result").empty();
// 검색어 가져오기
var keyword = $("#book-name").val();
// 검색어가 비었을 경우가 아니라면
if(keyword != ''){
// 첫 검색은 page=1
page = 1;
$.ajax({
url : "/writing/search/" + keyword +"/" + page,
type : "get",
dataType : "xml",
success : function(data){
// 검색된 도서 총 개수
var cnt = $(data).find('total').text();
$("#cntAll").val(cnt);
// item으로 검색된 도서 파싱
$(data).find('item').each(function(){
var title = $(this).find("title").text();
var author = $(this).find("author").text();
var img = $(this).find("image").text();
// 검색된 도서 <li>로 append
$("#srch-result").append("<li class='srchList' value=" + title + " 저자 : " + author
+"> <img src='" + img + "' height='50'> </li>");
});
},
error: function(e){
alert("도서명을 가져오지 못했습니다.");
}
});
} else {
// 검색어가 비었다면 검색결과 비워주기
$("#srch-result").empty();
}
});
}
JSP
'스프링(Spring) 공부' 카테고리의 다른 글
| [Spring Security] 권한에 따른 정보 감추기(authorize 사용) (0) | 2021.03.09 |
|---|---|
| 파일 저장하기 (0) | 2021.01.17 |
| 파일 업로드 설정하기 (0) | 2021.01.17 |
| POST 한글깨짐 해결 (0) | 2021.01.16 |
| POST 입력 (0) | 2021.01.16 |