스프링 콘트롤러에서 클라이언트에게 자동으로 JSON 문자열로 응답하도록 설정하기
개요
스프링의 콘트롤러 메소드에 @ResponseBody 라는 Annotation 을 선언하면 해당 메소드가 리턴하는 문자열은 응답 바디를 구성하게 되므로 클라이언트에게 직접 응답을 전송하는 용도로 사용할 수 있다.
또한 @ResponseBody 를 사용하면서 동시에 Jackson 라이브러리를 사용하면 콘트롤러가 리턴하는 객체는 JSON 문자열로 변환되어 클라이언트에게 전달되므로 AJAX 등을 이용하여 JSON문자열을 수신하기를 바라는 클라이언트에게 적용하면 보다 편리하고 코드량도 줄일 수 있다
사용되는 라이브러리 (pom.xml에 다음 요소를 추가)
http://mvnrepository.com/ 사이트에서 'jackson' 으로 검색하여 아래의 요소를 얻을 수 있다
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.3</version>
</dependency>
서버측에서 JSON 문자열을 처리하거나 JSON문자열을 생성하려면 Json-Simple 과 같은 라이브러리를 아래처럼 사용하면 된다
http://mvnrepository.com/ 사이트에서 'json simple' 으로 검색하여 dependency 엘리먼트를 pom.xml 에 추가하면 사용할 수 있다
코드에서 사용하는 방법을 참조하면 별다른 학습과정 없이 쉽게 사용할 수 있다 http://micropilot.tistory.com/category/JSON/JSON%2003,%20JSON-Simple%20Intro
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
servlet-context.xml 에 선언할 요소
<mvc:annotation-driven/>
JsonController.java
package org.kdea.json;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class JsonController {
/*
Jackson 라이브러리를 설치한다
메소드에 @ResponseBody 를 적용한다
<mvc:annotation-driven/> 을 servlet-context.xml 에 선언한다
이렇게 설정하면 스프링은 리턴되는 객체(도메인 오브젝트, List, Map 등)를 json 문자열로 자동으로
변환하여 클라이언트에게 전송한다.
이 경우 별도의 jsp 와 같은 View를 연결하지 않아도 된다
*/
@RequestMapping(value="/json/login", method=RequestMethod.GET)
public String login() {
return "json/ajax_client";
}
@RequestMapping(value="/json/login", method=RequestMethod.POST, produces="application/json; charset=utf8")
@ResponseBody //이 메소드가 리턴하는 값을 json 문자열로 변환하여 클라이언트에게 전송한다
public User login(User user) { // User 를 파라미터로 선언할 필요은 없다
return user; // 뷰가 연결되는 것이 아니라 응답 데이터에 해당하는 객체를 리턴한다
}
}
User.java
package org.kdea.json;
public class User {
private String id;
private String pwd;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
ajax_client.jsp ( 아래의 코드에서 사용한 jquery-2.1.1.min.js 파일은 webapp/resources/ 안에 두고 서블릿 설정파일에 resources 경로를 등록하면 된다)
<%@ 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">
<title>Insert title here</title>
<script src="<c:url value="/resources/jquery-2.1.1.min.js"/>"></script>
<script type="text/javascript">
function toJson_submit(){
ajax_request();
}
function ajax_request(){
var usrId = loginForm.id.value;
var usrPwd = loginForm.pwd.value;
$.ajax(
{
url:'login.do',
type:'POST',
data:{'id':usrId, 'pwd':usrPwd},
dataType:'text',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success :function(resData){
alert(resData);
/* dataType 속성을 'json' 으로 한 경우에는 다음과 같이 사용할 수 있다
alert("아이디="+resData.id + ", 암호="+resData.pwd);
*/
},
error :function(hxr, status, error){ alert("에러:"+error); }
}
);
}
</script>
</head>
<body>
<form name="loginForm">
ID <input type="text" name="id">
PWD <input type="password" name="pwd">
<input type="button" value="SUBMIT" onclick="toJson_submit()">
</form>
</body>
</html>