解如何利用 XML 和 JavaScript Object Notation 在 Ajax 客户端和 Java 服务器之间传输数据(代码)(Oracle)。

 ---------------------------------ajaxUtil-----------------------------------------------------------------------------------

 // ajaxUtil.js

 var debug = true;

 function sendHttpRequest(method, url, params, callback) {
var request;
if (window.XMLHttpRequest)
request = new XMLHttpRequest();
else if (window.ActiveXObject)
request = new ActiveXObject("Microsoft.XMLHTTP");
else
return null; if (method)
method = method.toUpperCase();
else
method = "GET";
var fullURL = url;
if (params && method == "GET")
fullURL += "?" + buildQueryString(params);
var async = false;
if (callback)
async = true;
request.open(method, fullURL, async); function calbackWrapper() {
if (async && request.readyState == 4) {
if (request.status == 200)
callback(request);
else
reportError(request, url, params);
}
}
if (async)
request.onreadystatechange = calbackWrapper; var body = null;
if (method == "POST") {
request.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
if (params)
body = buildQueryString(params);
}
request.send(body);
if (!async && (request.readyState != 4
|| request.status != 200)) {
reportError(request, url, params);
return null;
}
return request;
} function buildQueryString(params) {
var query = "";
for (var i = 0; i < params.length; i++) {
query += (i > 0 ? "&" : "")
+ escape(params[i].name) + "="
+ escape(params[i].value);
}
return query;
} function reportError(request, url, params) {
if (debug) {
if (request.status != 200) {
if (request.statusText)
alert(request.statusText);
else
alert("HTTP Status: " + request.status);
} else
alert("Response Error");
if (params)
url += "?" + buildQueryString(params);
document.location = url;
}
} function abortRequest(request) {
function doNothing() {
}
request.onreadystatechange = doNothing;
request.abort();
delete feedRequest;
} function escapeXML(content) {
if (content == undefined)
return "";
if (!content.length || !content.charAt)
content = new String(content);
var result = "";
var length = content.length;
for (var i = 0; i < length; i++) {
var ch = content.charAt(i);
switch (ch) {
case '&':
result += "&amp;";
break;
case '<':
result += "&lt;";
break;
case '>':
result += "&gt;";
break;
case '"':
result += "&quot;";
break;
case '\'':
result += "&apos;";
break;
default:
result += ch;
}
}
return result;
} function parse(xml) {
var dom;
try {
dom = new ActiveXObject("Microsoft.XMLDOM");
dom.async = false;
dom.loadXML(xml);
} catch (error) {
try {
var parser = new DOMParser();
dom = parser.parseFromString(xml, "text/xml");
delete parser;
} catch (error2) {
if (debug)
alert("XML parsing is not supported.");
}
}
return dom;
} function serialize(dom) {
var xml = dom.xml;
if (xml == undefined) {
try {
var serializer = new XMLSerializer();
xml = serializer.serializeToString(dom);
delete serializer;
} catch (error) {
if (debug)
alert("DOM serialization is not supported.");
}
}
return xml;
} -----------------------ajaxLogic--------------------------------------------------------------------------- // ajaxLogic.js var ctrlURL = "ajaxCtrl.jsp";
var feedRequest = null; function sendInfoRequest(symbols, callback) {
if (feedRequest)
abortRequest(feedRequest);
var params = new Array();
for (var i = 0; i < symbols.length; i++)
params[i] = {
name: "symbol",
value: symbols[i]
};
feedRequest = sendHttpRequest(
"GET", ctrlURL, params, callback);
} function sendSaveRequest(xml) {
var params = [ { name: "xml", value: xml } ];
var saveRequest = sendHttpRequest("POST", ctrlURL, params);
if (saveRequest)
delete saveRequest;
} function sendLoadRequest() {
var model = null;
var loadRequest = sendHttpRequest("GET", ctrlURL);
if (loadRequest) {
model = eval(loadRequest.responseText);
delete loadRequest;
}
return model;
} ------------------------------ajaxCtrl----------------------------------------------------------------------------------- <%-- ajaxCtrl.jsp --%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
<%@ taglib prefix="feed" uri="/WEB-INF/feed.tld" %> <tags:setHeader name="Cache-Control" value="no-cache"/> <jsp:useBean id="dataFeed" scope="application"
class="ajaxapp.feed.DataFeed" />
<jsp:useBean id="dataModel" scope="session"
class="ajaxapp.model.DataModel" /> <c:choose>
<c:when test="${!empty param.symbol}">
${feed:getData(dataFeed, paramValues.symbol)}
</c:when>
<c:when test="${!empty param.xml}">
<c:set target="${dataModel}"
property="data"
value="${param.xml}" />
</c:when>
<c:otherwise>
${dataModel.data}
</c:otherwise>
</c:choose>
-----------------------------------domTest.jsp-------------------------------------------------- <html>
<head> <script src="ajaxUtil.js">
</script> </head>
<body> <script language="javascript">
var xml = "<element>da<!--comment-->ta&amp;"
+ "<![CDATA[cdata]]></element>"; var dom = parse(xml);
var element = dom.documentElement; var childNodes = element.childNodes;
var text = "";
for (var i = 0; i < childNodes.length; i++)
if (childNodes[i].nodeValue) {
var type = childNodes[i].nodeType;
if (type == 3 || type == 4)
text += childNodes[i].nodeValue;
} document.writeln("<p>Original:<br>");
document.writeln(escapeXML(xml));
document.writeln("<p>Serialized:<br>");
document.writeln(escapeXML(serialize(dom)));
document.writeln("<p>Text:<br>");
document.writeln(text);
</script> </body>
</html>
-----------------------------feedTest--------------------------------------------------------------------------- <html>
<head> <style>
TD { text-align: right; }
</style> <script src="ajaxUtil.js">
</script> <script src="ajaxLogic.js">
</script> <script language="javascript"> var symbols = [ "AAAA", "BBBB", "CCCC" ]; function onLoad() {
sendInfoRequest(symbols, updateInfo);
setInterval("sendInfoRequest(symbols, updateInfo)", 5000);
} function updateInfo(request) {
var shares = eval(request.responseText);
var table = "<table border=1 cellpadding=5>";
table += "<tr>";
table += "<th>Symbol</th>";
table += "<th>Trend</th>";
table += "<th>Last Price</th>";
table += "</tr>";
for (var i = 0; i < shares.length; i++) {
var share = shares[i];
var symbol = escapeXML(share.symbol)
var trend = share.trend > 0 ? "+" : "-";
var lastPrice = new Number(share.lastPrice).toFixed(2);
table += "<tr>";
table += "<td>" + symbol + "</td>";
table += "<td>" + trend + "</td>";
table += "<td>" + lastPrice + "</td>";
table += "</tr>";
}
table += "</table>";
document.getElementById("table").innerHTML = table;
} </script> </head> <body onLoad="onLoad()"> <div id="table">
</div> </body>
</html>
--------------------------------------------ModelTest-------------------------------------------------------------------------------------- <html>
<head> <script src="ajaxUtil.js">
</script> <script src="ajaxLogic.js">
</script> <script language="javascript"> function attribute(name, value) {
return " " + name + "=\"" + escapeXML(value) + "\"";
} function buildPortfolioDoc(stocks) {
var xml = "<portfolio>";
for (var i = 0; i < stocks.length; i++) {
var stock = stocks[i];
xml += "<stock ";
xml += attribute("symbol", stock.symbol);
xml += attribute("shares", stock.shares);
xml += attribute("paidPrice", stock.paidPrice);
xml += "/>";
}
xml += "</portfolio>";
return xml;
} </script> </head>
<body> <p>Saved portfolio: <br>
<script language="javascript">
var savedStocks = [
{ symbol: "AAAA", shares: 1, paidPrice: 10 },
{ symbol: "BBBB", shares: 2, paidPrice: 20 },
{ symbol: "CCCC", shares: 3, paidPrice: 30 }
];
var xml = buildPortfolioDoc(savedStocks);
sendSaveRequest(xml);
document.writeln(escapeXML(xml));
</script> <p>Loaded portfolio: <br>
<script language="javascript">
var loadedStocks = sendLoadRequest();
document.writeln(escapeXML(buildPortfolioDoc(loadedStocks)));
</script> </body>
</html>
------------------------------------queryTest---------------------------------------------------------------------- <html>
<head> <script src="ajaxUtil.js">
</script> </head>
<body> <script language="javascript"> var someParams = [
{ name: "name", value: "John Smith" },
{ name: "email", value: "john@company.com" },
{ name: "phone", value: "(123) 456 7890" }
]; someQuery = buildQueryString(someParams); document.writeln(someQuery); </script> </body>
</html>
-------------------------------------------------------------------- java:src package ajaxapp.feed; import ajaxapp.util.JSONEncoder; import java.util.*; public class DataFeed implements java.io.Serializable {
private HashMap<String, ShareBean> shareMap; public DataFeed() {
shareMap = new HashMap<String, ShareBean>();
} public synchronized String getData(String symbols[]) {
JSONEncoder json = new JSONEncoder();
json.startArray();
for (int i = 0; i < symbols.length; i++) {
String symbol = symbols[i];
ShareBean share = shareMap.get(symbol);
if (share == null) {
share = new ShareBean(symbol);
shareMap.put(symbol, share);
}
json.startObject();
json.property("symbol", share.getSymbol());
json.property("trend", share.getTrend());
json.property("lastPrice", share.getLastPrice());
json.endObject();
}
json.endArray();
return json.toString();
} public static String getData(
DataFeed feed, String symbols[]) {
return feed.getData(symbols);
} }
package ajaxapp.feed; public class ShareBean implements java.io.Serializable {
private String symbol;
private int trend;
private double lastPrice; public ShareBean(String symbol) {
this.symbol = symbol;
trend = 1;
lastPrice = Math.random() * 100;
} public String getSymbol() {
return symbol;
} public int getTrend() {
return trend;
} public double getLastPrice() {
lastPrice += trend * Math.random() * 0.1;
if (Math.random() < 0.2)
trend = -trend;
return lastPrice;
} }
package ajaxapp.model; import ajaxapp.util.JSONEncoder;
import ajaxapp.util.XMLUtil; import org.w3c.dom.*;
import org.xml.sax.*; import javax.xml.parsers.*;
import javax.xml.xpath.*; import java.io.*;
import java.util.*;
import java.util.logging.*; public class DataModel implements java.io.Serializable {
private static final String SCHEMA_NAME
= "/ajaxapp/model/portfolio.xsd";
private static DocumentBuilderFactory parserFactory; private ArrayList<StockBean> stockList; public DataModel() {
stockList = new ArrayList<StockBean>();
} private static Document parsePortfolioDoc(String xml)
throws IOException, SAXException,
ParserConfigurationException {
synchronized (DataModel.class) {
if (parserFactory == null)
parserFactory = XMLUtil.newParserFactory(SCHEMA_NAME);
}
DocumentBuilder parser = XMLUtil.newParser(parserFactory);
InputSource in = new InputSource(new StringReader(xml));
return parser.parse(in);
} public synchronized void setData(String xml)
throws IOException, SAXException,
ParserConfigurationException,
XPathExpressionException {
try {
ArrayList<StockBean> stockList
= new ArrayList<StockBean>();
Document doc = parsePortfolioDoc(xml);
NodeList nodeList = XMLUtil.evalToNodeList(
"/portfolio/stock", doc);
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
StockBean stock = new StockBean();
stock.setSymbol(
XMLUtil.evalToString("@symbol", node));
stock.setShares(
(int) XMLUtil.evalToNumber("@shares", node));
stock.setPaidPrice(
XMLUtil.evalToNumber("@paidPrice", node));
stockList.add(stock);
}
this.stockList = stockList;
} catch (Exception e) {
Logger.global.logp(Level.SEVERE, "DataModel", "setData",
e.getMessage(), e);
}
} public synchronized String getData() {
JSONEncoder json = new JSONEncoder();
json.startArray();
for (int i = 0; i < stockList.size(); i++) {
StockBean stock = stockList.get(i);
json.startObject();
json.property("symbol", stock.getSymbol());
json.property("shares", stock.getShares());
json.property("paidPrice", stock.getPaidPrice());
json.endObject();
}
json.endArray();
return json.toString();
} }
package ajaxapp.model; public class StockBean implements java.io.Serializable {
private String symbol;
private int shares;
private double paidPrice; public String getSymbol() {
return symbol;
} public void setSymbol(String symbol) {
this.symbol = symbol;
} public int getShares() {
return shares;
} public void setShares(int shares) {
this.shares = shares;
} public double getPaidPrice() {
return paidPrice;
} public void setPaidPrice(double paidPrice) {
this.paidPrice = paidPrice;
} }
---------------proloi.xsd----------------------------------------- <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="portfolio" type="portfolioType"/> <xsd:complexType name="portfolioType">
<xsd:sequence>
<xsd:element name="stock"
minOccurs="0" maxOccurs="unbounded">
<xsd:complexType>
<xsd:attribute name="symbol"
type="xsd:string" use="required"/>
<xsd:attribute name="shares"
type="xsd:positiveInteger" use="required"/>
<xsd:attribute name="paidPrice"
type="xsd:decimal" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType> </xsd:schema>
--------------------JSON------------------------------------------------------------------------------ package ajaxapp.util; public class JSONEncoder {
private StringBuilder buf; public JSONEncoder() {
buf = new StringBuilder();
} public void character(char ch) {
switch (ch) {
case '\'':
case '\"':
case '\\':
buf.append('\\');
buf.append(ch);
break;
case '\t':
buf.append('\\');
buf.append('t');
break;
case '\r':
buf.append('\\');
buf.append('r');
break;
case '\n':
buf.append('\\');
buf.append('n');
break;
default:
if (ch >= 32 && ch < 128)
buf.append(ch);
else {
buf.append('\\');
buf.append('u');
for (int j = 12; j >= 0; j-=4) {
int k = (((int) ch) >> j) & 0x0f;
int c = k < 10 ? '0' + k : 'a' + k - 10;
buf.append((char) c);
}
}
}
} public void string(String str) {
int length = str.length();
for (int i = 0; i < length; i++)
character(str.charAt(i));
} public void literal(Object value) {
if (value instanceof String) {
buf.append('"');
string((String) value);
buf.append('"');
} else if (value instanceof Character) {
buf.append('\'');
character(((Character) value).charValue());
buf.append('\'');
} else
buf.append(value.toString());
} private void comma() {
buf.append(',');
} private void deleteLastComma() {
if (buf.length() > 0)
if (buf.charAt(buf.length()-1) == ',')
buf.deleteCharAt(buf.length()-1);
} public void startObject() {
buf.append('{');
} public void property(String name, Object value) {
buf.append(name);
buf.append(':');
literal(value);
comma();
} public void endObject() {
deleteLastComma();
buf.append('}');
comma();
} public void startArray() {
buf.append('[');
} public void element(Object value) {
literal(value);
comma();
} public void endArray() {
deleteLastComma();
buf.append(']');
comma();
} public String toString() {
deleteLastComma();
return buf.toString();
} public void clear() {
buf.setLength(0);
} }
package ajaxapp.util; import oracle.xml.jaxp.JXDocumentBuilderFactory;
import oracle.xml.parser.schema.XMLSchema;
import oracle.xml.parser.schema.XSDBuilder; import org.w3c.dom.*;
import org.xml.sax.*; import javax.xml.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.validation.*;
import javax.xml.xpath.*; import java.io.*;
import java.util.*;
import java.util.logging.*; public class XMLUtil { public static ErrorHandler newErrorHandler() {
return new ErrorHandler() {
public void warning(SAXParseException e)
throws SAXException {
Logger.global.warning(e.getMessage());
} public void error(SAXParseException e)
throws SAXException {
throw e;
} public void fatalError(SAXParseException e)
throws SAXException {
throw e;
}
};
} public static InputStream getResourceAsStream(String name)
throws IOException {
InputStream in = XMLUtil.class.getResourceAsStream(name);
if (in == null)
throw new FileNotFoundException(name);
return in;
} protected static SchemaFactory schemaFactory;
static {
schemaFactory = SchemaFactory.newInstance(
XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory.setErrorHandler(newErrorHandler());
} public static Schema newSchema(String name)
throws IOException, SAXException {
Schema schema;
InputStream in = getResourceAsStream(name);
try {
schema = schemaFactory.newSchema(new StreamSource(in));
} finally {
in.close();
}
return schema;
} public static XMLSchema newOracleSchema(String name)
throws IOException, SAXException {
XMLSchema schema;
InputStream in = getResourceAsStream(name);
try {
XSDBuilder builder = new XSDBuilder();
schema = builder.build(new InputSource(in));
} catch (Exception e) {
throw new SAXException(e);
} finally {
in.close();
}
return schema;
} public static DocumentBuilderFactory newParserFactory(
String schemaName) throws IOException, SAXException {
DocumentBuilderFactory parserFactory
= DocumentBuilderFactory.newInstance();
try {
parserFactory.setSchema(newSchema(schemaName));
} catch (UnsupportedOperationException e) {
if (parserFactory instanceof JXDocumentBuilderFactory) {
parserFactory.setAttribute(
JXDocumentBuilderFactory.SCHEMA_OBJECT,
newOracleSchema(schemaName));
}
}
return parserFactory;
} public static DocumentBuilder newParser(
DocumentBuilderFactory parserFactory)
throws ParserConfigurationException {
DocumentBuilder parser = parserFactory.newDocumentBuilder();
parser.setErrorHandler(newErrorHandler());
return parser;
}; protected static XPathFactory xpathFactory;
static {
xpathFactory = XPathFactory.newInstance();
} public static XPath newXPath() {
return xpathFactory.newXPath();
} public static String evalToString(String expression,
Object context) throws XPathExpressionException {
return (String) newXPath().evaluate(expression, context,
XPathConstants.STRING);
} public static boolean evalToBoolean(String expression,
Object context) throws XPathExpressionException {
return ((Boolean) newXPath().evaluate(expression, context,
XPathConstants.BOOLEAN)).booleanValue();
} public static double evalToNumber(String expression,
Object context) throws XPathExpressionException {
return ((Double) newXPath().evaluate(expression, context,
XPathConstants.NUMBER)).doubleValue();
} public static Node evalToNode(String expression,
Object context) throws XPathExpressionException {
return (Node) newXPath().evaluate(expression, context,
XPathConstants.NODE);
} public static NodeList evalToNodeList(String expression,
Object context) throws XPathExpressionException {
return (NodeList) newXPath().evaluate(expression, context,
XPathConstants.NODESET);
} public static TransformerFactory serializerFctory;
static {
serializerFctory = TransformerFactory.newInstance();
} public static void serialize(Node node, OutputStream out)
throws TransformerException {
Transformer serializer = serializerFctory.newTransformer();
Properties serializerProps = new Properties();
serializerProps.put(OutputKeys.METHOD, "xml");
serializer.setOutputProperties(serializerProps);
Source source = new DOMSource(node);
Result result = new StreamResult(out);
serializer.transform(source, result);
} }
上一篇:(转)JAVA AJAX教程第三章—AJAX详细讲解


下一篇:线上Bug无法复现怎么办?老司机教你一招,SpringBoot远程调试不用愁!