관리 메뉴

공부 기록장 💻

[Spring] Thymeleaf View에 List로 담은 객체 전달하기 - 알라딘 도서 검색 Open API 활용 본문

# Tech Studies/Java Spring • Boot

[Spring] Thymeleaf View에 List로 담은 객체 전달하기 - 알라딘 도서 검색 Open API 활용

dream_for 2023. 2. 14. 15:38

알라딘 도서 검색 Open API를 활용하여 얻은 도서 목록 결과를 List에 담아 View에 전달하기


알라딘 도서 검색 Open API를 이용해 특정 쿼리에 대한 검색 결과로 JSON 형태의 데이터를 받아,
이를 Thymeleaf Template Engine을 이용해 직접 만든 View에 결과를 출력하고자 한다.

각 도서 객체는 "BookSearchResult" 에 담았으며, 이를 List에 담아 전체 도서 목록 결과를 출력해보자.

Form

메인 홈에서 query를 입력하는 form은 다음과 같다. /book/result 경로로 GET 요청을 보내는 form이다.

<form action="/book/result" method="GET">
<div class="form-group">
<div id="book-search-form">
  <label for="query">키워드 입력: </label>
  <input type="text" size=50 id="query" name="query" placeholder="검색하고 싶은 도서 키워드를 입력하세요">
  <button type="submit">완료</button>
</div>
</div>
</form>

Controller

Controller은 다음과 같이 작성해주었다.
@RequestMapping의 GET 요청 "/book/result" 경로로 보내는 메서드이며,
파라미터로 받은 Query 객체(검색에 사용되는 키워드 입력 값)를 BookSearchService의 searchBooks()로 전달하여
결과 값으로 얻은 도서 목록들 results를 model의 attribute으로 등록한다.

@RequestMapping(value = "/book/result", method = RequestMethod.GET)
public String showResult(Model model, BookSearchQuery query) {
    List<BookSearchedResult> results = bookSearchService.searchBooks(query);
    model.addAttribute("results", results);
    return "book/result";
}

Service - searchBooks() 메서드

BookSearchService의 searchBooks() 메서드는 간략하게 아래와 같다.

query 키워드로 검색하여 얻게 된 도서 객체 BookSearchResult를 ArrayList results 객체에 담게 된다.
도서의 title부터 link, author 등 json data에서 얻은 값들을 가져와 result의 필드들을 초기한다.
최종적으로, 검색 결과 도서 목록들을 담은 results를 반환한다.

public List<BookSearchedResult> searchBooks(BookSearchQuery query) {

	// 알라딘 도서 검색 open API를 호출하여 json data 결과를 얻어 item에 해당하는 값들을 가져옴
    
    
    ArrayList<BookSearchedResult> results = new ArrayList<>();

    for (int i = 0; i < items.length(); i++) {
        BookSearchedResult result = new BookSearchedResult();

        JSONObject item = items.getJSONObject(i);
        result.setTitle(item.getString("title"));
        result.setLink(item.getString("link"));
        result.setAuthor(item.getString("author"));
        result.setPubDate(item.getString("pubDate"));
        result.setIsbn(item.getString("isbn"));
        result.setCategoryId(item.getLong("categoryId"));
        result.setCategoryName(item.getString("categoryName"));
        result.setPublisher(item.getString("publisher"));
        result.setPriceSales(item.getLong("priceSales"));

        results.add(result);
    }

    return results;
}

Thymeleaf Html View


thymeleaf Template 언어를 이용해 작성한 html 페이지는 다음과 같다.
List<BookSearchResult> 에 담긴 각 객체들 Controller에서 results 라는 이름의 model의 속성 attribute으로 추가해주었고,

thymeleaf template 문법 each을 이용해 <tr th:each="result : ${results}> 를 작성하여  ${results} 에 담긴 모든 도서 객체들 각각을  result  담아 results를 돌며 속성 값들을 출력하게 된다.

<!-- -->

<table>
  <thead>
    <tr style="background-color:lightgray">

		<!-- table head들 -->
        
    </tr>
  </thead>
  
  <tbody style="text-align:center">
    <tr th:if="${response=='NoData'}">
      <td> 해당 쿼리에 부합하는 도서 결과가 없습니다. 다시 올바르게 검색해주세요. </td>
    </tr>
    <tr th:each="result : ${results}">
      <td> <span style="font-weight:bold" th:text="${result.title}"> Title </span></td>
      <td>
        <img th:src="@{${result.coverLink}}" alt="no image"/>
      </td>
      <td> <span th:text="${result.author}"> Author </span></td>
      <td> <span th:text="${result.publisher}"> Publisher </span></td>
      <td> <span th:text="${result.pubDate}"> Published Date </span></td>
      <td> <span th:text="${result.isbn}"> ISBN Number </span></td>
      <td> <span th:text="${result.priceSales}"> Price Sales </span></td>
      <td> <span th:text="${result.categoryId}"> Category ID </span></td>
      <td> <span th:text="${result.categoryName}"> Category Name </span></td>
      <td> <a th:href="${result.link}"> Book Info </a></td>
    </tr>
  </tbody>
</table>

<!-- -->


결과 VIEW


chatGPT 라는 키워드로 검색하여 얻은 도서 목록들을 보여주는 최종적인 결과 화면은 다음과 같다.

/book/result?query=chatGPT 경로로 진입했을 때, 알라딘 도서 검색 API를 해당 query에 맞게 호출하여 얻은

도서 결과들이 목록에 잘 표시 되었다.


[참고자료]
https://www.baeldung.com/thymeleaf-list

728x90
반응형
Comments