Spring

Spring(5)_MVC(2)_Ajax&JSON

clumsy0g 2019. 12. 12. 16:57

View

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- jQuery 2.2.0 -->
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<title>지도 춤 검색</title>
</head>
<body>

.............
<ul>
<c:forEach items="${boardList}" var="board">
<li>${board.ktd_name}<button onclick="boardInfo(${board.ktd_id})">개요</button></li>
</c:forEach>
</ul>

<script type="text/javascript">
function boardInfo(ktd_id) {

    $.ajax({
        type : "POST",
        dataType : "json",
        url : "/mapSearch/json",
        data : {
            data : { "ktd_id" : ktd_id }
        },

        success : function(data){alert("성공")},
        error : function(e){alert(e);}

    });

}



</script>

</body>
</html>

dataType : 주고 받을 데이터의 타입을 json으로 명시하였다

data : 보낼 데이터를 자바스크립트 객체로 명시하는데 { attr명 : attr값 }. attr값에 json 객체를 명시해준다.

여기서는 직접 json객체를 만들었지만, 자바스크립트 객체로 만든뒤 이를 쉽게 JSON 객체로 변환하는 함수(JSON.stringfy())도 있으니 참고. ( https://sugerent.tistory.com/66)

서버(자바)단에서는, 이 요청에 응답을 할 때 자바객체로 응답할수도 있고, 바로 JSON객체를 return 할 수 도 있다.

Jackson2는 자바 객체 <---> JSON 변환에 필요한 라이브러리이다.

스프링 MVC의 Converter가 이 라이브러리를 이용해서 두객체사이의 변환을 수행한다.

pom.xml

    <!-- json -->
    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.3.3</version>
    </dependency>    

반드시 스프링 버전과 맞는 JSON 라이브러리를 사용해야한다.

스프링 3.1.1 버전에서는 org.codehaus.jackson을 사용해야하며, 3.2.x 버전 대 이상에서는 jackson.core로 사용.

( 링크 참고 : https://okky.kr/article/386796?note=1219848 )

따라서, 3.9.7로 버전 변경하고 pom.xml에 jackson.core 추가.