基于Java的Ajax框架之JSON-RPC(一)

官方主页:http://oss.metaparadigm.com/jsonrpc/

先看一个简单的例子:

如下图所示建立工程:

代码如下:

web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.4" 
  3.     xmlns="http://java.sun.com/xml/ns/j2ee" 
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
  6.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  7.   <welcome-file-list>
  8.     <welcome-file>index.html</welcome-file>
  9.   </welcome-file-list>
  10. </web-app>

index.html

  1. <html>
  2. <head>
  3. <title>ajax测试</title>
  4. <script language="JavaScript" src="json.js">
  5. </script>
  6. <script language="JavaScript">
  7.     var xmlrequest;
  8.     function createXMLHttpRequest()
  9.     {
  10.         if(window.XMLHttpRequest)
  11.         { //Mozilla 浏览器
  12.             xmlrequest = new XMLHttpRequest();
  13.         }
  14.         else if (window.ActiveXObject)
  15.         {
  16.             // IE浏览器
  17.             try
  18.             {
  19.                 xmlrequest = new ActiveXObject("Msxml2.XMLHTTP");
  20.             }
  21.             catch (e)
  22.             {
  23.                 try
  24.                 {
  25.                     xmlrequest = new ActiveXObject("Microsoft.XMLHTTP");
  26.                 }
  27.                 catch (e) {}
  28.             }
  29.         }
  30.     }
  31.     function change(id)
  32.     {
  33.         var params = {
  34.             countryId : id
  35.         }
  36.         createXMLHttpRequest(); 
  37.         var uri = "server.jsp";
  38.         xmlrequest.open("POST", uri, true); 
  39.         xmlrequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  40.         xmlrequest.onreadystatechange = processResponse;
  41.         alert(params.toJSONString());
  42.         xmlrequest.send(params.toJSONString());     
  43.     }
  44.     function processResponse()
  45.     {
  46.         if(xmlrequest.readyState == 4)
  47.         {
  48.             if(xmlrequest.status == 200)
  49.             {
  50.                 var cityList = xmlrequest.responseText.split("$");
  51.                 var displaySelect = document.getElementById("second");
  52.                 for(i = displaySelect.length - 1; i >= 0; i--)
  53.                 {
  54.                     displaySelect.options[i] = null;
  55.                 }
  56.                 for (var i = 0 ; i < cityList.length ; i++)
  57.                 {
  58.                     option = document.createElement("option");
  59.                     var city = cityList[i].replace(/[/r/n]/g,"");//去回车
  60.                     citycity = city.replace(/[ ]/g,"");//去空格
  61.                     txtNode = document.createTextNode(city);
  62.                     option.appendChild(txtNode);
  63.                     displaySelect.appendChild(option);
  64.                 }
  65.             }
  66.         }
  67.     }
  68. </script>
  69. </head>
  70. <body>
  71. <select name="first" id="first" onChange="change(this.value);" style="width:80" size="3">
  72.     <option value="1" selected>中国</option>
  73.     <option value="2">美国</option>
  74.     <option value="3">日本</option>
  75. </select>
  76. <select name="second" id="second" style="width:80" size="3">
  77. </select>
  78. </body>
  79. </html>

json.js(下载自:http://www.json.org/json.js

源代码如下:

  1. /*
  2.     json.js
  3.     2008-05-25
  4.     Public Domain
  5.     No warranty expressed or implied. Use at your own risk.
  6.     This file has been superceded by http://www.JSON.org/json2.js
  7.     See http://www.JSON.org/js.html
  8.     This file adds these methods to JavaScript:
  9.         array.toJSONString(whitelist)
  10.         boolean.toJSONString()
  11.         date.toJSONString()
  12.         number.toJSONString()
  13.         object.toJSONString(whitelist)
  14.         string.toJSONString()
  15.             These methods produce a JSON text from a JavaScript value.
  16.             It must not contain any cyclical references. Illegal values
  17.             will be excluded.
  18.             The default conversion for dates is to an ISO string. You can
  19.             add a toJSONString method to any date object to get a different
  20.             representation.
  21.             The object and array methods can take an optional whitelist
  22.             argument. A whitelist is an array of strings. If it is provided,
  23.             keys in objects not found in the whitelist are excluded.
  24.         string.parseJSON(filter)
  25.             This method parses a JSON text to produce an object or
  26.             array. It can throw a SyntaxError exception.
  27.             The optional filter parameter is a function which can filter and
  28.             transform the results. It receives each of the keys and values, and
  29.             its return value is used instead of the original value. If it
  30.             returns what it received, then structure is not modified. If it
  31.             returns undefined then the member is deleted.
  32.             Example:
  33.             // Parse the text. If a key contains the string 'date' then
  34.             // convert the value to a date.
  35.             myData = text.parseJSON(function (key, value) {
  36.                 return key.indexOf('date') >= 0 ? new Date(value) : value;
  37.             });
  38.     This file will break programs with improper for..in loops. See
  39.     http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
  40.     This file creates a global JSON object containing two methods: stringify
  41.     and parse.
  42.         JSON.stringify(value, replacer, space)
  43.             value       any JavaScript value, usually an object or array.
  44.             replacer    an optional parameter that determines how object
  45.                         values are stringified for objects without a toJSON
  46.                         method. It can be a function or an array.
  47.             space       an optional parameter that specifies the indentation
  48.                         of nested structures. If it is omitted, the text will
  49.                         be packed without extra whitespace. If it is a number,
  50.                         it will specify the number of spaces to indent at each
  51.                         level. If it is a string (such as '/t' or ' '),
  52.                         it contains the characters used to indent at each level.
  53.             This method produces a JSON text from a JavaScript value.
  54.             When an object value is found, if the object contains a toJSON
  55.             method, its toJSON method will be called and the result will be
  56.             stringified. A toJSON method does not serialize: it returns the
  57.             value represented by the name/value pair that should be serialized,
  58.             or undefined if nothing should be serialized. The toJSON method
  59.             will be passed the key associated with the value, and this will be
  60.             bound to the object holding the key.
  61.             For example, this would serialize Dates as ISO strings.
  62.                 Date.prototype.toJSON = function (key) {
  63.                     function f(n) {
  64.                         // Format integers to have at least two digits.
  65.                         return n < 10 ? '0' + n : n;
  66.                     }
  67.                     return this.getUTCFullYear()   + '-' +
  68.                          f(this.getUTCMonth() + 1) + '-' +
  69.                          f(this.getUTCDate())      + 'T' +
  70.                          f(this.getUTCHours())     + ':' +
  71.                          f(this.getUTCMinutes())   + ':' +
  72.                          f(this.getUTCSeconds())   + 'Z';
  73.                 };
  74.             You can provide an optional replacer method. It will be passed the
  75.             key and value of each member, with this bound to the containing
  76.             object. The value that is returned from your method will be
  77.             serialized. If your method returns undefined, then the member will
  78.             be excluded from the serialization.
  79.             If the replacer parameter is an array, then it will be used to
  80.             select the members to be serialized. It filters the results such
  81.             that only members with keys listed in the replacer array are
  82.             stringified.
  83.             Values that do not have JSON representations, such as undefined or
  84.             functions, will not be serialized. Such values in objects will be
  85.             dropped; in arrays they will be replaced with null. You can use
  86.             a replacer function to replace those with JSON values.
  87.             JSON.stringify(undefined) returns undefined.
  88.             The optional space parameter produces a stringification of the
  89.             value that is filled with line breaks and indentation to make it
  90.             easier to read.
  91.             If the space parameter is a non-empty string, then that string will
  92.             be used for indentation. If the space parameter is a number, then
  93.             the indentation will be that many spaces.
  94.             Example:
  95.             text = JSON.stringify(['e', {pluribus: 'unum'}]);
  96.             // text is '["e",{"pluribus":"unum"}]'
  97.             text = JSON.stringify(['e', {pluribus: 'unum'}], null, '/t');
  98.             // text is '[/n/t"e",/n/t{/n/t/t"pluribus": "unum"/n/t}/n]'
  99.             text = JSON.stringify([new Date()], function (key, value) {
  100.                 return this[key] instanceof Date ?
  101.                     'Date(' + this[key] + ')' : value;
  102.             });
  103.             // text is '["Date(---current time---)"]'
  104.         JSON.parse(text, reviver)
  105.             This method parses a JSON text to produce an object or array.
  106.             It can throw a SyntaxError exception.
  107.             The optional reviver parameter is a function that can filter and
  108.             transform the results. It receives each of the keys and values,
  109.             and its return value is used instead of the original value.
  110.             If it returns what it received, then the structure is not modified.
  111.             If it returns undefined then the member is deleted.
  112.             Example:
  113.             // Parse the text. Values that look like ISO date strings will
  114.             // be converted to Date objects.
  115.             myData = JSON.parse(text, function (key, value) {
  116.                 var a;
  117.                 if (typeof value === 'string') {
  118.                     a =
  119. /^(/d{4})-(/d{2})-(/d{2})T(/d{2}):(/d{2}):(/d{2}(?:/./d*)?)Z$/.exec(value);
  120.                     if (a) {
  121.                         return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
  122.                             +a[5], +a[6]));
  123.                     }
  124.                 }
  125.                 return value;
  126.             });
  127.             myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
  128.                 var d;
  129.                 if (typeof value === 'string' &
  130.                         value.slice(0, 5) === 'Date(' &
  131.                         value.slice(-1) === ')') {
  132.                     d = new Date(value.slice(5, -1));
  133.                     if (d) {
  134.                         return d;
  135.                     }
  136.                 }
  137.                 return value;
  138.             });
  139.     It is expected that these methods will formally become part of the
  140.     JavaScript Programming Language in the Fourth Edition of the
  141.     ECMAScript standard in 2008.
  142.     This is a reference implementation. You are free to copy, modify, or
  143.     redistribute.
  144.     This code should be minified before deployment.
  145.     See http://javascript.crockford.com/jsmin.html
  146.     USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU
  147.     DO NOT CONTROL.
  148. */
  149. /*jslint evil: true */
  150. /*global JSON */
  151. /*members "", "/b", "/t", "/n", "/f", "/r", "/"", JSON, "//", call,
  152.     charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes,
  153.     getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length,
  154.     parse, parseJSON, propertyIsEnumerable, prototype, push, replace, slice,
  155.     stringify, test, toJSON, toJSONString, toString
  156. */
  157. if (!this.JSON) {
  158. // Create a JSON object only if one does not already exist. We create the
  159. // object in a closure to avoid global variables.
  160.     JSON = function () {
  161.         function f(n) {
  162.             // Format integers to have at least two digits.
  163.             return n < 10 ? '0' + n : n;
  164.         }
  165.         Date.prototype.toJSON = function (key) {
  166.             return this.getUTCFullYear()   + '-' +
  167.                  f(this.getUTCMonth() + 1) + '-' +
  168.                  f(this.getUTCDate())      + 'T' +
  169.                  f(this.getUTCHours())     + ':' +
  170.                  f(this.getUTCMinutes())   + ':' +
  171.                  f(this.getUTCSeconds())   + 'Z';
  172.         };
  173.         var cx = /[/u0000/u00ad/u0600-/u0604/u070f/u17b4/u17b5/u200c-/u200f/u2028-/u202f/u2060-/u206f/ufeff/ufff0-/uffff]/g,
  174.             escapeable = /[///"/x00-/x1f/x7f-/x9f/u00ad/u0600-/u0604/u070f/u17b4/u17b5/u200c-/u200f/u2028-/u202f/u2060-/u206f/ufeff/ufff0-/uffff]/g,
  175.             gap,
  176.             indent,
  177.             meta = {    // table of character substitutions
  178.                 '/b''//b',
  179.                 '/t''//t',
  180.                 '/n''//n',
  181.                 '/f''//f',
  182.                 '/r''//r',
  183.                 '"' : '//"',
  184.                 '//': ''
  185.             },
  186.             rep;
  187.         function quote(string) {
  188. // If the string contains no control characters, no quote characters, and no
  189. // backslash characters, then we can safely slap some quotes around it.
  190. // Otherwise we must also replace the offending characters with safe escape
  191. // sequences.
  192.             escapeable.lastIndex = 0;
  193.             return escapeable.test(string) ?
  194.                 '"' + string.replace(escapeable, function (a) {
  195.                     var c = meta[a];
  196.                     if (typeof c === 'string') {
  197.                         return c;
  198.                     }
  199.                     return '//u' + ('0000' +
  200.                             (+(a.charCodeAt(0))).toString(16)).slice(-4);
  201.                 }) + '"' :
  202.                 '"' + string + '"';
  203.         }
  204.         function str(key, holder) {
  205. // Produce a string from holder[key].
  206.             var i,          // The loop counter.
  207.                 k,          // The member key.
  208.                 v,          // The member value.
  209.                 length,
  210.                 mind = gap,
  211.                 partial,
  212.                 value = holder[key];
  213. // If the value has a toJSON method, call it to obtain a replacement value.
  214.             if (value && typeof value === 'object' &
  215.                     typeof value.toJSON === 'function') {
  216.                 value = value.toJSON(key);
  217.             }
  218. // If we were called with a replacer function, then call the replacer to
  219. // obtain a replacement value.
  220.             if (typeof rep === 'function') {
  221.                 value = rep.call(holder, key, value);
  222.             }
  223. // What happens next depends on the value's type.
  224.             switch (typeof value) {
  225.             case 'string':
  226.                 return quote(value);
  227.             case 'number':
  228. // JSON numbers must be finite. Encode non-finite numbers as null.
  229.                 return isFinite(value) ? String(value) : 'null';
  230.             case 'boolean':
  231.             case 'null':
  232. // If the value is a boolean or null, convert it to a string. Note:
  233. // typeof null does not produce 'null'. The case is included here in
  234. // the remote chance that this gets fixed someday.
  235.                 return String(value);
  236. // If the type is 'object', we might be dealing with an object or an array or
  237. // null.
  238.             case 'object':
  239. // Due to a specification blunder in ECMAScript, typeof null is 'object',
  240. // so watch out for that case.
  241.                 if (!value) {
  242.                     return 'null';
  243.                 }
  244. // Make an array to hold the partial results of stringifying this object value.
  245.                 gap += indent;
  246.                 partial = [];
  247. // If the object has a dontEnum length property, we'll treat it as an array.
  248.                 if (typeof value.length === 'number' &
  249.                         !(value.propertyIsEnumerable('length'))) {
  250. // The object is an array. Stringify every element. Use null as a placeholder
  251. // for non-JSON values.
  252.                     length = value.length;
  253.                     for (i = 0; i < length; i += 1) {
  254.                         partial[i] = str(i, value) || 'null';
  255.                     }
  256. // Join all of the elements together, separated with commas, and wrap them in
  257. // brackets.
  258.                     v = partial.length === 0 ? '[]' :
  259.                         gap ? '[/n' + gap +
  260.                                 partial.join(',/n' + gap) + '/n' +
  261.                                     mind + ']' :
  262.                               '[' + partial.join(',') + ']';
  263.                     gap = mind;
  264.                     return v;
  265.                 }
  266. // If the replacer is an array, use it to select the members to be stringified.
  267.                 if (rep && typeof rep === 'object') {
  268.                     length = rep.length;
  269.                     for (i = 0; i < length; i += 1) {
  270.                         k = rep[i];
  271.                         if (typeof k === 'string') {
  272.                             v = str(k, value, rep);
  273.                             if (v) {
  274.                                 partial.push(quote(k) + (gap ? ': ' : ':') + v);
  275.                             }
  276.                         }
  277.                     }
  278.                 } else {
  279. // Otherwise, iterate through all of the keys in the object.
  280.                     for (k in value) {
  281.                         if (Object.hasOwnProperty.call(value, k)) {
  282.                             v = str(k, value, rep);
  283.                             if (v) {
  284.                                 partial.push(quote(k) + (gap ? ': ' : ':') + v);
  285.                             }
  286.                         }
  287.                     }
  288.                 }
  289. // Join all of the member texts together, separated with commas,
  290. // and wrap them in braces.
  291.                 v = partial.length === 0 ? '{}' :
  292.                     gap ? '{/n' + gap +
  293.                             partial.join(',/n' + gap) + '/n' +
  294.                             mind + '}' :
  295.                           '{' + partial.join(',') + '}';
  296.                 gap = mind;
  297.                 return v;
  298.             }
  299.         }
  300. // Return the JSON object containing the stringify and parse methods.
  301.         return {
  302.             stringify: function (value, replacer, space) {
  303. // The stringify method takes a value and an optional replacer, and an optional
  304. // space parameter, and returns a JSON text. The replacer can be a function
  305. // that can replace values, or an array of strings that will select the keys.
  306. // A default replacer method can be provided. Use of the space parameter can
  307. // produce text that is more easily readable.
  308.                 var i;
  309.                 gap = '';
  310.                 indent = '';
  311. // If the space parameter is a number, make an indent string containing that
  312. // many spaces.
  313.                 if (typeof space === 'number') {
  314.                     for (i = 0; i < space; i += 1) {
  315.                         indent += ' ';
  316.                     }
  317. // If the space parameter is a string, it will be used as the indent string.
  318.                 } else if (typeof space === 'string') {
  319.                     indent = space;
  320.                 }
  321. // If there is a replacer, it must be a function or an array.
  322. // Otherwise, throw an error.
  323.                 rep = replacer;
  324.                 if (replacer && typeof replacer !== 'function' &
  325.                         (typeof replacer !== 'object' ||
  326.                          typeof replacer.length !== 'number')) {
  327.                     throw new Error('JSON.stringify');
  328.                 }
  329. // Make a fake root object containing our value under the key of ''.
  330. // Return the result of stringifying the value.
  331.                 return str('', {'': value});
  332.             },
  333.             parse: function (text, reviver) {
  334. // The parse method takes a text and an optional reviver function, and returns
  335. // a JavaScript value if the text is a valid JSON text.
  336.                 var j;
  337.                 function walk(holder, key) {
  338. // The walk method is used to recursively walk the resulting structure so
  339. // that modifications can be made.
  340.                     var k, v, value = holder[key];
  341.                     if (value && typeof value === 'object') {
  342.                         for (k in value) {
  343.                             if (Object.hasOwnProperty.call(value, k)) {
  344.                                 v = walk(value, k);
  345.                                 if (v !== undefined) {
  346.                                     value[k] = v;
  347.                                 } else {
  348.                                     delete value[k];
  349.                                 }
  350.                             }
  351.                         }
  352.                     }
  353.                     return reviver.call(holder, key, value);
  354.                 }
  355. // Parsing happens in four stages. In the first stage, we replace certain
  356. // Unicode characters with escape sequences. JavaScript handles many characters
  357. // incorrectly, either silently deleting them, or treating them as line endings.
  358.                 cx.lastIndex = 0;
  359.                 if (cx.test(text)) {
  360.                     text = text.replace(cx, function (a) {
  361.                         return '//u' + ('0000' +
  362.                                 (+(a.charCodeAt(0))).toString(16)).slice(-4);
  363.                     });
  364.                 }
  365. // In the second stage, we run the text against regular expressions that look
  366. // for non-JSON patterns. We are especially concerned with '()' and 'new'
  367. // because they can cause invocation, and '=' because it can cause mutation.
  368. // But just to be safe, we want to reject all unexpected forms.
  369. // We split the second stage into 4 regexp operations in order to work around
  370. // crippling inefficiencies in IE's and Safari's regexp engines. First we
  371. // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
  372. // replace all simple value tokens with ']' characters. Third, we delete all
  373. // open brackets that follow a colon or comma or that begin the text. Finally,
  374. // we look to see that the remaining characters are only whitespace or ']' or
  375. // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
  376.                 if (/^[/],:{}/s]*$/.
  377. test(text.replace(///(?:["bfnrt]|u[0-9a-fA-F]{4})/g, '@').
  378. replace(/"[^"///n/r]*"|true|false|null|-?/d+(?:/./d*)?(?:[eE][+/-]?/d+)?/g, ']').
  379. replace(/(?:^|:|,)(?:/s*/[)+/g, ''))) {
  380. // In the third stage we use the eval function to compile the text into a
  381. // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
  382. // in JavaScript: it can begin a block or an object literal. We wrap the text
  383. // in parens to eliminate the ambiguity.
  384.                     j = eval('(' + text + ')');
  385. // In the optional fourth stage, we recursively walk the new structure, passing
  386. // each name/value pair to a reviver function for possible transformation.
  387.                     return typeof reviver === 'function' ?
  388.                         walk({'': j}, '') : j;
  389.                 }
  390. // If the text is not JSON parseable, then a SyntaxError is thrown.
  391.                 throw new SyntaxError('JSON.parse');
  392.             }
  393.         };
  394.     }();
  395. }
  396. // Augment the basic prototypes if they have not already been augmented.
  397. // These forms are obsolete. It is recommended that JSON.stringify and
  398. // JSON.parse be used instead.
  399. if (!Object.prototype.toJSONString) {
  400.     Object.prototype.toJSONString = function (filter) {
  401.         return JSON.stringify(this, filter);
  402.     };
  403.     Object.prototype.parseJSON = function (filter) {
  404.         return JSON.parse(this, filter);
  405.     };
  406. }

server.jsp

  1. <%@ page contentType="text/html; charset=GBK" language="java"
  2.     import="org.json.*,java.io.*"%>
  3. <%
  4.     System.out.println("--------------");
  5.     StringBuffer sb = new StringBuffer();
  6.     String line = null;
  7.     BufferedReader reader = request.getReader();
  8.     while ((line = reader.readLine()) != null) {
  9.         sb.append(line);
  10.     }
  11.     String json = sb.toString();
  12.     JSONObject jsonObject = new JSONObject(json);
  13.     int city = jsonObject.getInt("countryId");
  14.     switch (city) {
  15.         case 1:
  16.             out.print("上海$广州$北京");
  17.         break;
  18.         case 2:
  19.             out.print("华盛顿$纽约$加洲");
  20.         break;
  21.         case 3:
  22.             out.print("东京$大板$福冈");
  23.         break;
  24.     }
  25. %>

关于Json,参见:http://www.json.org/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值