Spring MVC - JSON 통신

Programming/Java 2016.12.10 17:29 Posted by 파란크리스마스

JSONData 추상 클래스 생성

Factory 패턴에서 반환 가능한 형태로 만들기 위해서 추상 클래스를 사용하기때문에 아래와 같이 추상 클래스를 생성

package com.iot.json;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

public abstract class JSONData {
	
	private static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
	
	public abstract JSONObject getJSON(HttpServletRequest request, HttpServletResponse response);
	
	public JSONObject getJSONObject(Map<String, Object> map) {
		JSONObject jobj = new JSONObject();
		//loop a Map
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			if (entry.getValue() instanceof java.sql.Date) {
				//
				jobj.put(entry.getKey(), fromCalendar((Date) entry.getValue()));
			} else {
				jobj.put(entry.getKey(), entry.getValue());
			}
		}
		return jobj;
	}
	
	public static String fromCalendar(final Date date) {
		String formatted = formatter.format(date);
		return formatted.substring(0, 22) + ":" + formatted.substring(22);
	}
}

JSONSample 클래스 생성

간단하게 테스트나 이해를 돕기 위해서 JSONData 추상 클래스를 상속받아서 Sample 클래스를 생성

package com.iot.json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
public class JSONSample extends JSONData {

	@Override
	public JSONObject getJSON(HttpServletRequest request, HttpServletResponse response) {
		JSONArray arrayObj = new JSONArray();
		
		JSONArray data = new JSONArray();
		data.add("Tiger Nixon");
		data.add("System Architect");
		data.add("Edinburgh");
		data.add("5421");
		data.add("2011/04/25");
		data.add("$320,800");
		arrayObj.add(data);
		
		data = new JSONArray();
		data.add("Garrett Winters");
		data.add("Accountant");
		data.add("Tokyo");
		data.add("8422");
		data.add("2011/07/25");
		data.add("$170,750");
		arrayObj.add(data);
		
		JSONObject jobj_data = new JSONObject();
		jobj_data.put("data", arrayObj);
		
		return jobj_data;
	}
}

JSONFactory 클래스 생성

Factory 패턴으로 cmd 값에 따라 해당 JSONData를 구현한 객체를 반환

package com.iot.json;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class JSONFactory {
	
	@Autowired
	private JSONSample jSONSample;
	
	public JSONData getJSONData(String cmd) {
		
		System.out.println("cmd = " + cmd);
		
		if (true) {
			return jSONSample;
		}
		
		return jSONSample;
	}
}

JSONController 클래스 생성

json 형태로 데이터 반환

package com.iot.json;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class JSONController {
	
	@Autowired
	private JSONFactory jSONFactory;

	@ResponseBody
	@RequestMapping(value="/json.iot", method=RequestMethod.GET, produces="application/json; charset=utf-8")
	public String service(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws IOException {
		
		/*
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		String reg_id = auth.getName();
		*/
		
		/*
		Enumeration<String> keys = request.getParameterNames();
		while(keys.hasMoreElements()) {
			String key = keys.nextElement();
			System.out.println("param = " + key + "/" + request.getParameter(key));
		}
		*/
		
		String cmd = request.getParameter("cmd");
		if (cmd==null) {
			cmd = "";
		}
		
		JSONData json = jSONFactory.getJSONData(cmd);
		
		return json.getJSON(request, response).toString();
	}

}

iot-servlet.xml 내용 추가

json 관련 패키지가 자동으로 스프링컨테이너에 로딩 되도록 WEB-INF/iot-servlet.xml 파일에에 아래 내용을 추가

<context:component-scan base-package="com.iot.json"/>

	<!-- 컨트롤더 package 자동으로 스프링 컨테이너 등록 -->
	<context:component-scan base-package="com.iot.controller"/>
	<context:component-scan base-package="com.iot.json"/>

Sample 데이터 확인

JSONUser 클래스 추가

AJAX로 사용자 추가하는 클래스를 만들기 위해서  JSONData 추상 클래스를 상속받아서 JSONUser 클래스를 생성

package com.iot.json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.iot.db.domain.UserInfo;
import com.iot.db.service.UserInfoService;

import net.sf.json.JSONObject;

public class JSONUser extends JSONData {
	
	public static String COMMAND = "user";
	
	@Autowired
	private UserInfoService service;

	@Override
	public JSONObject getJSON(HttpServletRequest request, HttpServletResponse response) {
		String subcmd = request.getParameter("subcmd");
		System.out.println("subcmd = " + subcmd);	
		
		JSONObject jobj_data = null;
		if (subcmd.equals("add")) {
			jobj_data = getAddData(request, response);
		}
			
		return jobj_data;
	}

	private JSONObject getAddData(HttpServletRequest request, HttpServletResponse response) {
		
		String errStr = null;
		
		try {
			UserInfo userinfo = new UserInfo();
			userinfo.setName(request.getParameter("name"));
			
			service.insertUserInfo(userinfo);
		} catch (Exception e) {
			errStr = e.toString();
			e.printStackTrace();
		}
		
		JSONObject jobj_data = new JSONObject();
		jobj_data.put("success", (errStr == null ? true : false));
		
		return jobj_data;
	}

}

JSONFactory 수정

파라미터 cmd의 값이 user인 경우 JSONUser의 객체가 반환 되도록 코드 추가

package com.iot.json;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class JSONFactory {
	
	@Autowired
	private JSONUser jSONUser;
	
	@Autowired
	private JSONSample jSONSample;
	
	public JSONData getJSONData(String cmd) {
		
		System.out.println("cmd = " + cmd);
		
		if (JSONUser.COMMAND.equals(cmd)) { // JSONUser.COMMAND = user
			return jSONUser;
		} else {
			return jSONSample;
		}
		
		// return jSONSample;
	}
}

UserController 클래스 생성

사용자 관련 Controller 클래스 생성

package com.iot.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.iot.db.domain.CodeString;

@Controller
public class UserController {
	
	@RequestMapping(value = "/user_add_ajax.iot", method = RequestMethod.GET)
	public String user_add_ajax(ModelMap modelMap) throws Exception {
		return "/user_add_ajax";
	}

}

user_add_ajax.jsp 생성

사용자 추가 JSP 작성 - JQuery AJAX 통신

<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script  src="http://code.jquery.com/jquery-latest.min.js"></script>
<title>사용자추가</title>
<script type="text/javascript">
function user_add() {
	var form = document.uploadForm;
    //var form = new FormData(document.getElementById('uploadForm'));
	$.ajax({
	  url: "<c:url value="/json.iot"/>",
	  data: {
		cmd : "user",
		subcmd : "add",
		user_id : form.user_id.value,
		password : form.password.value,
		name : form.name.value,
		nickname : form.nickname.value
	  },
	  // data: form,
	  dataType: 'json',
	  contentType: false,
	  type: 'GET',
	  success: function (response) {
	    console.log('success');
	    console.log(response);
	  },
	  error: function (jqXHR) {
	    console.log('error');
	  }
	});
}
</script>
</head>
<body>

<h1>사용자 추가</h1>
<form id="uploadForm" name="uploadForm" method="get">
	<input type="hidden" name="cmd" value="user">
	<input type="hidden" name="subcmd" value="add">
	<table border="1">
		<tr>
			<td>사용자ID</td>
			<td>
				<input type="text" name="user_id"/>
			</td>
		</tr>
		<tr>
			<td>암호</td>
			<td>
				<input type="text" name="password"/>
			</td>
		</tr>
		<tr>
			<td>사용자이름</td>
			<td>
				<input type="text" name="name"/>
			</td>
		</tr>
		<tr>
			<td>별명</td>
			<td>
				<input type="text" name="nickname"/>
			</td>
		</tr>
		<!-- 
		<tr>
			<td>사진</td>
			<td>
				<input type="file" name="photo"/>
			</td>
		</tr>
		-->
	</table>
	<br/>
	<input type="button" value="사용자추가" onclick="javascript:user_add();"/>
</form>

</body>
</html>


저작자 표시
신고


 

티스토리 툴바