文件一览
- JSONExample.java
- jsonExample.html
JSONExample.java
package ajaxbook.chap3;
import java.io.BufferedReader;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONExample extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String json = readJSONStringFromRequestBody(req);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
String responseText = "You have a " + jsonObject.getInt("year") + " "
+ jsonObject.getString("make") + " " + jsonObject.getString("model")+ " "
+ "that is " + jsonObject.getString("color") + " in color";
resp.setContentType("text/xml");
resp.getWriter().print(responseText);
} catch(JSONException pe) {
System.out.println("JSONException: " + pe.toString());
}
}
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();
}
}
jsonExample.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <script language="JavaScript" src="./js/json2.js" type="text/javascript"></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() { var car = getCarObject(); var carAsJSON = JSON.stringify(car); alert("Car Object as JSON:\n "+carAsJSON); createXMLHttpRequest(); var url = "JSONExample?timeStamp="+new Date().getTime(); xmlHttp.open("POST",url,true); xmlHttp.onreadystatechange=handleStateChange; xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;"); xmlHttp.send(carAsJSON); } 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; } 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); } </script> <head> </head> <body> <h1>Select the types of pets in your home:</h1> <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>
其中java里要导入org.json.jar包,JavaScript要引入json2.js文件,这两个文件都在下面的附件里。