工程目錄:
show.jsp :
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%><html><head><title>Insert title here</title><script type="text/javascript" src="js/prototype1.6.js"></script><script>function getXmlHttpRequest(){var xhr=null;if((typeof XMLHttpRequest)!='undefined'){xhr=new XMLHttpRequest();}else{xhr=new ActiveXObject("Microsoft.XMLHttp");}return xhr;}var intervalId;function show(){intervalId=setInterval(getShareInfo,1000);}function stopShow(){clearInterval(intervalId);}function getShareInfo(){var xhr=getXmlHttpRequest();xhr.onreadystatechange=function(){if(xhr.readyState==4){var jsonStr=xhr.responseText;var share=jsonStr.evalJSON();$('d1').innerHTML="股票名稱:"+share.shareName+"<br>股票價格:"+share.sharePrice+"<br>時間:"+share.date;}}xhr.open("post","show",true);xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xhr.send(null);}</script></head><body onload="show();"><div style="width:250px;height:70px;border:1px solid black" id="d1"></div><input type="button" value="停止報價" onclick="stopShow();"></body></html>
Share.java :
public class Share {private String shareName;private double sharePrice;private Date date;public Date getDate() {return date;}public void setDate(Date date) {this.date = date;}public String getShareName() {return shareName;}public void setShareName(String shareName) {this.shareName = shareName;}public double getSharePrice() {return sharePrice;}public void setSharePrice(double sharePrice) {this.sharePrice = sharePrice;}public Share() {super();}public Share(String shareName, double sharePrice, Date date) {super();this.shareName = shareName;this.sharePrice = sharePrice;this.date = date;}}
DateProcessor.java :
public class DateProcessor implements JsonValueProcessor {private String pattern="yyyy-MM-dd HH:mm:ss";public void setPattern(String pattern) {this.pattern = pattern;}@Overridepublic Object processArrayValue(Object arg0, JsonConfig arg1) {Date date=(Date)arg0;SimpleDateFormat sdf=new SimpleDateFormat(pattern);return sdf.format(date);}@Overridepublic Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {Date date=(Date)arg1;SimpleDateFormat sdf=new SimpleDateFormat(pattern);return sdf.format(date);}}
ShowServlet.java :
public class ShowServlet extends HttpServlet {public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {Random random=new Random();String shareName="share"+random.nextInt(99999);double sharePrice=Math.ceil(random.nextDouble()*10);Share share=new Share(shareName,sharePrice,new Date());DateProcessor processor=new DateProcessor();JsonConfig config=new JsonConfig();config.registerJsonValueProcessor(Date.class,processor);JSONObject json=JSONObject.fromObject(share,config);response.setContentType("text/html;charset=UTF-8");PrintWriter pw=response.getWriter();pw.println(json.toString());pw.close();}}
為ShowServlet映射的url為show。
資料轉換涉及兩個過程:
① 伺服器端將Java對象Share轉換為符合json文法的字串,並發送給用戶端。
② 瀏覽器接收到符合json文法的字串,利用evalJSON( )函數將字串轉換為JavaScript對象,並及時更新頁面資料。
當然,上面的程式在實際中無意義,它僅僅為了示範json是如何做資料交換的。