13-1 json 내용 추가합니다.

60 views
Skip to first unread message

베시시

unread,
Nov 9, 2011, 10:36:08 PM11/9/11
to IBKSYSTEM
민원이 들어와서 13장에 중요한 내용중에 하나인 json 간략 예제를 올립니다.
그럼 스터디 시간에 같이 실행해요~!

======111.jsp======

<%@ page contentType="text/html;charset=euc-kr" session="false"%>
<html>
<head>
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript">
var xmlHttp = null;
function createXMLHttpRequest() {
if(window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}

function doJSON() {
var car = getCarObject();

var carAsJSON = JSON.stringify(car);
//alert(" JSON 표현:\n" + carAsJSON);

var url = "./222.jsp?timeStamp=" + new Date().getTime();

createXMLHttpRequest();
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-
urlencoded");
xmlHttp.send(carAsJSON);
}

function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
parseResults();
}
}
}

function parseResults() {
var responseDiv = document.getElementById("serverResponse");
if(responseDiv.hasChildNodes()) {
responseDiv.removeChild(responseDiv.childNodes[0]);
}

var responseText = document.createTextNode(xmlHttp.responseText);
responseDiv.appendChild(responseText);
}

function getCarObject() {
return new Car("현대", "소나타", "2006", "흰색");
}

function Car(make, model, year, color) {
this.make = make;
this.model = model;
this.year = year;
this.color = color;
}
</script>
</head>

<body>
<form action="#">
<input type="button" value="보내기" onclick="doJSON();"/>
</form>
응답
<div id="serverResponse"></div>
<br/>

</body>
</html>

========222.jsp===============


<% request.setCharacterEncoding("UTF-8"); %>
<%@page import="org.json.JSONException"%>
<%@page import="org.json.JSONObject"%>
<%@page import="java.io.BufferedReader"%>
<%@ page contentType="text/html; charset=euc-kr" %>
<%
String json = readJSONStringFromRequestBody(request);

JSONObject jsonObject = null;

try {
jsonObject = new JSONObject(json);
} catch(JSONException pe) {
System.out.println("ParseException: " + pe.toString());
}

String responseText = "당신은 " + jsonObject.getInt("year") + "년식 "
+ jsonObject.getString("make") + " " +
jsonObject.getString("model")
+ "를 가지고 있습니다. " + "차의 색깔은 " + jsonObject.getString("color") + " 입니
다.";

%>
<%= responseText %>
<%!
private String readJSONStringFromRequestBody(HttpServletRequest
request) {
StringBuffer json = new StringBuffer();
String line = null;

try {
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null) {
json.append(line);
}
} catch(Exception e) {
System.out.println("Error reading JSON string: " + e.toString());
}
return json.toString();
}
%>



수고하세여
Reply all
Reply to author
Forward
0 new messages