x<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.2</version>
</dependency>
xxxxxxxxxx
@RequestMapping(value = "/listJson")
@ResponseBody
public List<Map<String, Object>> listJson(@RequestParam Map<String, Object> map) {
List<Map<String, Object>> list = this.bookService.list(map);
return list;
}
xxxxxxxxxx
package com.sample.book.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.sample.book.service.BookService;
@RestController
public class BoorControllerApi {
@Autowired
BookService bookService;
@RequestMapping(value = "/listGet")
public List<Map<String, Object>> listGet(@RequestParam Map<String, Object> map) {
List<Map<String, Object>> list = this.bookService.list(map);
for(Map m:list) {
System.out.println(m);
}
return list;
}
}
xxxxxxxxxx
@RequestMapping(value = "/listAjax")
public ModelAndView listAjax(@RequestParam Map<String, Object> map) {
ModelAndView mav = new ModelAndView();
mav.setViewName("/book/listAjax");
return mav;
}
xxxxxxxxxx
<%@ page pageEncoding="UTF-8" contentType="text/html;charset=utf-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html lang="ko">
<head>
<title>책 목록</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
const getJson = function () {
const keyword = $('#keyword').val();
const param = {keyword: keyword};
$.ajax({
type:'GET',
url:'listGet',
dataType:'json',
data:param,
success: function (response) {
let book_info ='<tr>'
for(book of response){
console.log(book);
const title = book['title'];
const category = book['category'];
const price = book['price']
book_info +='<tr>'
book_info += '<td>'+title+'</td>';
book_info += '<td>'+category+'</td>';
book_info += '<td>'+price+'</td>';
book_info +='/<tr>'
}
$('#book_info').html(book_info);
},
error: function (request, status, error) {
console.log(request, status,error);
}
});
}
$(function () {
getJson();
});
</script>
</head>
<body>
<h1>책 목록(AJAX)</h1>
<p>
<form>
<input type="text" placeholder="검색" name="keyword" id="keyword" value="${keyword}" />
<input type="button" value="검색" onclick="getJson()"/>
</form>
</p>
<table>
<thead>
<tr>
<td>제목</td>
<td>카테고리</td>
<td>가격</td>
</tr>
</thead>
<tbody id="book_info">
</tbody>
</table>
<p>
<a href="create">생성</a>
</p>
</body>
</html>