1. jsonExample.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<title>JSON Example</title>
<script type="text/javascript" src="../js/json2.js"></script>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function doJSON() {
alert("begin doJSON");
var car = getCarObject();
alert(car);
//Use the JSON JavaScript library to stringify the Car object
var carAsJSON = JSON.stringify(car);
alert("Car object as JSON:/n " + carAsJSON);
var url = "JSONExample?timeStamp=" + new Date().getTime();
alert(url);
createXMLHttpRequest();
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
xmlHttp.send(carAsJSON);
alert("end doJSON");
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
parseResults();
}
}
}
function parseResults() {
alert("begin parseResults");
var responseDiv = document.getElementById("serverResponse");
if(responseDiv.hasChildNodes()) {
responseDiv.removeChild(responseDiv.childNodes[0]);
}
var responseText = document.createTextNode(xmlHttp.responseText);
responseDiv.appendChild(responseText);
alert("end parseResults");
}
function getCarObject() {
return new Car("Dodge", "Coronet R/T", 1968, "yellow");
}
function Car(make, model, year, color) {
this.make = make;
this.model = model;
this.year = year;
this.color = color;
}
</script>
</head>
<body>
<br/><br/>
<form action="#">
<input type="button" value="Click here to send JSON data to the server" οnclick="doJSON();"/>
</form>
<h2>Server Response:</h2>
<div id="serverResponse"></div>
</body>
</html>
2.JSONExample.java
package ajaxbook.chap3;
import java.io.*;
//import java.net.*;
//import java.text.ParseException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONExample extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String json = readJSONStringFromRequestBody(request);
//Use the JSON-Java binding library to create a JSON object in Java
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
}
catch (JSONException e) {
e.printStackTrace();
}
String responseText;
try {
responseText = "You have a " + jsonObject.getInt("year") + " "
+ jsonObject.getString("make") + " " + jsonObject.getString("model")
+ " " + " that is " + jsonObject.getString("color") + " in color.";
response.setContentType("text/xml");
response.getWriter().print(responseText);
} catch (JSONException e) {
e.printStackTrace();
}
}
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();
}
}
3. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>TestAjax</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>GetAndPostExample</servlet-name>
<servlet-class>ajaxbook.chap3.GetAndPostExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetAndPostExample</servlet-name>
<url-pattern>/GetAndPostExample</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>PostingXMLExample</servlet-name>
<servlet-class>ajaxbook.chap3.PostingXMLExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PostingXMLExample</servlet-name>
<url-pattern>/PostingXMLExample</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>JSONExample</servlet-name>
<servlet-class>ajaxbook.chap3.JSONExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JSONExample</servlet-name>
<url-pattern>/pages/JSONExample</url-pattern>
</servlet-mapping>
</web-app>