본문 바로가기

개발/Framework

[Spring] 스프링에서 AJAX 응답데이터 보내기 (JSON, GSON 사용) / @ResponseBody

* 메이븐(Mavon) 사용 기준

1. pom.xml파일 <dependencies> 태그 안에 JSON / GSON 라이브러리 추가

<!-- JSON 라이브러리 -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>


<!-- GSON 라이브러리 -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>





* 기존의 JSP/Servlet에서 사용한 방식

: JSON (JavaScript Object Notation 자바스크립트객체표기법) 형태로 담아서 응답

- JSONArray => [값, 값, 값, ...]  => 자바에서의 HashMap과 유사 / add()메소드 사용

@RequestMapping("ajax1.do")
public void ajaxMethod1(String name, int age, HttpServletResponse response) throws IOException {
    // * JSONArray 객체 생성
    JSONArray jArr = new JSONArray();
    jArr.add(name); // ["홍길동"]
    jArr.add(age);  // ["홍길동", 15] 

    response.setContentType("application/json; charset=UTF-8");
    response.getWriter().print(jArr);
}


- JSONObject => {키:값, 키:값, ...}  => 자바에서의 ArrayList와 유사 / put()메소드 사용

@RequestMapping("ajax1.do")
public void ajaxMethod1(String name, int age, HttpServletResponse response) throws IOException {
    // * JSONObject 객체 생성
    JSONObject jObj = new JSONObject();
    jObj.put("name", name);
    jObj.put("age", age);

    response.setContentType("application/json; charset=UTF-8");
    response.getWriter().print(jObj); //[[Prototype]]:Object
}




2. 스프링에서 AJAX 응답데이터 보내기

@ResponseBody

메서드 반환 값이 web response body에 바인딩되어야 함을 나타내는 주석입니다. 서블릿 환경에서 annotated handler 메서드에 대해 지원됩니다.
Annotation which indicates that a method return value should be bound to the web response body. Supported for annotated handler methods in Servlet environments.

: 반환하는 값이 응답페이지가 될 문자열이 아니라 Response Body에 보낼 데이터임을 나타내는 어노테이션
: View Resolver가 문자열을 페이지 경로로 자동완성 하고 JSP를 HTML로 변환하는 일련의 과정을 거치지 않고, 데이터로 전달됨


* 문자열로 내보내기

@ResponseBody 
@RequestMapping(value="ajax1.do", produces="text/html; charset=UTF-8")
public String ajaxMethod1(String name, int age) {
    return "응답 문자열 : " + name + "은(는) " + age + "살 입니다." ;
}


< JSON >


- 내가 정한 key값과 value값으로 데이터를 전달

* Spring에서의 JSON 사용 : 반환형을 String + toJSONString() 메소드 사용
toJSONString()

이 맵의 문자열 표현을 반환합니다. 문자열 표현은 대괄호("{}")로 둘러싸인 맵의 entrySet 뷰의 iterator가 반환하는 순서대로 키-값 매핑 목록으로 구성됩니다.
Returns a string representation of this map. The string representationconsists of a list of key-value mappings in the order returned by themap's entrySet view's iterator, enclosed in braces("{}").
@ResponseBody
@RequestMapping(value="ajax2.do", produces="application/json; charset=UTF-8")
public String ajaxMethod2(int num) {
    Member m = new Member("user01", "pass01", "홍길동", 15, "010-1231-1111");

    JSONObject jObj = new JSONObject();
    jObj.put("userId", m.getUserId());
    jObj.put("userPwd", m.getUserPwd());
    jObj.put("name", m.getName());
    jObj.put("age", m.getAge());
    jObj.put("phone", m.getPhone());

    return jObj.toJSONString();
}



< GSON >

- GSON이 객체(클래스)의 필드를 보고 필드명으로 key값을 쓰고, getter를 써서 value를 넣어주는 작업을 !!대신!! 해줌

* Spring에서의 GSON 사용 : 객체 전달

@ResponseBody
@RequestMapping(value="ajax2.do", produces="application/json; charset=UTF-8")
public String ajaxMethod2(int num) {

    Member m = new Member("user01", "pass01", "홍길동", 20, "010-1234-5678");
    return new Gson().toJson(m); 
}


* Spring에서의 GSON 사용 : 리스트 전달

@ResponseBody
@RequestMapping(value="ajax3.do", produces="application/json; charset=UTF-8")
public String ajaxMethod3() {

    ArrayList<Member> list = new ArrayList();
    list.add(new Member("user01", "pass01", "홍길동", 10, "010-1234-4567"));
    list.add(new Member("user02", "pass02", "김길동", 15, "010-1234-4568"));
    list.add(new Member("user03", "pass03", "강길동", 20, "010-1234-4569"));

    return new Gson().toJson(list);	
}