??xml version="1.0" encoding="utf-8" standalone="yes"?>
作? kissjava.com?
旉: 2005-05-12 12:31:15
出处: KissJava.com
责Q~辑: Icy
[文章D]
目前讉KXML文档的API分成两种讉K方式Q顺序的和Q意的讉KQ分别是QSAX和DOM。确认XML的合法性的规范是DTD (最初的机制Q作为XML规范被定?和不同的概要标准提案Q一U更新的机制Q它使用XML语法来做描述合法性准则的工作Q?nbsp;
XML和相兌|(x)消化字母汤(“字母汤”alphabet soup是一U罐头汤Q里面是切成ABC字母图案的细面条Q让朋友边喝汤Ҏ(gu)里面的字母排成单词来玩)
现在Q你已经对XML有了一个基本的理解Q需要对与XML相关的羃写单词代表的意义有一个更q认识。有很多的基于XML的工作要做,所以你需要学?fn)很多的知识?/P>
目前讉KXML文档的API分成两种讉K方式Q顺序的和Q意的讉KQ分别是QSAX和DOM。确认XML的合法性的规范是DTD (最初的机制Q作为XML规范被定?和不同的概要标准QSchema StandardsQ提案(一U更新的机制Q它使用XML语法来做描述合法性准则的工作Q?/P>
其它的一些未来的标准已经接近完成Q包括XSL标准Q一U徏立XML文档转换-例如XML文档转换到HTML或其他的XML文档Q?和指C文档如何提交的机制Q。XSL标准的{换部分(XSLT (+XPATH)Q已l完成ƈ且包含在本指南中。其他的接近完成的成果是XMLq接语言QXML Link LanguageQ规范(XML LinkingQ,q个规范可以在XML文档之间做连接?/P>
以上q些是你将要了解的初步内容。这部分也纵览了一些其它的感兴的提案Q包括HTMLcM标准QHTML-lookalike standardQ?- XHTML 和描qXML包含的信息的元标?- RDF。有些标准成果扩展了XML的能力,比如Xlink和Xpointer?/P>
最后,有很多的感兴的标准和标准提案徏立在XML之上Q包含同步的多媒体综合语aQSynchronized Multimedia Integration LanguageQ?- (SMIL)Q数学标记语aQMathematical Markup LanguageQ?- MathML Q可伸羃的向量图形(Scalable Vector GraphicsQ?- SVGQDrawML和许多的?sh)子商务标准?/P>
余下的部分你了解这些初步的更详l的l节。ؓ(f)了保持连贯性,q部分被分ؓ(f)如下斚wQ?BR>1. 基本标准
2. 概要标准
3. q接和显C标?BR>4. 知识标准
5. 建立在XML上的标准
基本标准
一些你需要熟(zhn)的基本标准?BR>SAX
针对XML的简单API(Simple API for XML)
q个API实际上一个协作品,它不是W3C的品。它被包含在里面是因为它拥有W3C的特征?/P>
你也可以把这个标准想象ؓ(f)XML的连l访问协议。它拥有在服务器中读写XML数据的最快的执行机制。也可以U它Z仉动协议,因ؓ(f)q个技术将在SAX parser中注册你的操作,注册完后Q当parser看到一个新的XML标记Ӟ或者遇C个错误,或者parser惛_诉你其他的事情)Qparser׃(x)调用你的回调Ҏ(gu)?/P>
DOM
文档对象模型QDocument Object ModelQ?BR>文档对象模型协议一个XML文档转换成一个对象集。然后你可以操作随意的操作这个对象模型。这个机制被UCؓ(f)“随意访问”协议,因ؓ(f)你能够在M时候访问数据的L部分。然后,你可以修攏V删除和插入数据?/P>
JDOM and dom4j
当文档对象模型(DOMQ提供非常强大的面向文档的处理的时候,它却不能提供更多的面向对象的化。Java开发者会(x)做更多的面向数据处理Q而不是面向书c、文章和其他的完全的文档Q他们发现面向对象的APIQ如:JDOM和dom4jQ更Ҏ(gu)使用和符合他们的需要?/P>
下面是JDOM和dom4j的不同:(x)
1. JDOM是更整齐、更y的API。在代码风格Qcoding styleQ重要的时候,JDOM是一个不错的选择?BR>2. JDOM是一个Java团体处理QJava Community Process--JCPQ初步。当完成Ӟ它将是一个认可的标准?BR>3. dom4j是一个更y、更快的实现Q它使用的范围很qѝ?BR>4. dom4j是一个基于制造商Qfactory-basedQ的实现。它更容易修改复杂的、特D目的的应用E序。在dom4j~写的时候,JDOMq没有用利用工厂(factoryQ来事例化分析器对象。所以,使用JDOMQ你L得到原始的分析器?/P>
关于JDOM的更多的信息Q?A >http://www.jdom.org/.
关于dom4j的更多的信息Q?A >http://dom4j.org/.
DTD
文档cd定义QDocument Type DefinitionQ?/P>
DTD规范是XML规范的一部分Q而不是一个单独的实体。另一斚wQ它是可选的?你可以一个没有DTD的XML文档。有很多的概要(SchemaQ标准提案来提供更灵zȝ规范。所以,你完全可以将它看成是单独的部分?/P>
一个DTD规范了不同种cȝXML标识和合法的标识的布局。你能够使用DTD来确定你不能产生一个非法的XMLl构。你也能够用它来确定你正在d得XMLl构是合法的?/P>
不幸的是Qؓ(f)一个复杂的文档指定一个DTD是非常的困难的。所以构Z个DTD在某U意义上讲是一门艺术。DTD可以出现在文档的前端Q作为序的一部分。它也可以作为单独的一个实体,或者在文档的序和外部的实体中同时存在?/P>
命名I间
命名I间标准允许你用两个或更多的XML标记集合~写XML文档。例如你产生一个基于XML的列表,q个列表使用的标记是另一个厂商提供的。在整个XML文档中“price”数据可能会(x)很多Q然而,你只是想昄针对一个结构的“price”数据。命名空间规范定义了一个限定名U的机制Q这样可以避免淆。这h们写的程序就可以正确的处理文档中的信息?/P>
最新的命名I间信息Q?A >http://www.w3.org/TR/REC-xml-names.
XSL
扩展样式表语aQExtensible Stylesheet LanguageQ?/P>
XML标准指定怎样识别数据Q而不是怎样昄数据。从另一斚w来说QHTML是告诉数据怎样昄而不是怎样识别数据。XSL标准有两部分QXSLT和XSL-FO。XSL-FOZ提供面上的多区域定义ƈ他们连接到一赗当一个文本流被导向这个集合,它首先流向第一个区域,在第一个区域被充满后会(x)导向W二个区域。像q样的对象被使用在新ȝ、一览表和杂志出版中?/P>
最新的XSL标准Q?A >http://www.w3.org/TR/WD-xsl
XSLT(+XPATH)
针对转换的扩展样式表语言QExtensible Stylesheet Language for TransformationsQ?/P>
XSLT的{换标准本质上来讲是一个{换机Ӟ它让你指定将一个XML标记转换成什么ƈ用来昄。例如,转换成HTML标识。不同的XSL格式能够以不同的方式昄同样的数据。(XPATH标准是一个寻址机制Q当你构造{换指令示?x)用到它。)
概要标准
一个DTD佉K证相关的单XML文档是否合法成ؓ(f)可能Q但是做h很难?/P>
一个DTD不能限制元素中的内容Q不能指定复杂的关系。例如,指定一?lt;book>中的<heading>必须包含?lt;title>?lt;author>Q而一?lt;chapter>中的<heading>紧紧需要一?lt;title>。在DTD中,你只能一ơ的指定<heading>的结构。DTD不是上下文敏感的Q因为DTD规范不是层次的?/P>
例如Q一个邮件地址包含几个“解析的字符数据QPCDATAQ”元素,DTD可能?x)像下面q样Q?BR><!ELEMENT mailAddress (name, address, zipcode)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT address (#PCDATA)>
<!ELEMENT zipcode (#PCDATA)>
像你看到的那Pq个规范是线性的。所以,在DTD中,如果你需要另一个“name”元素,那么你需要ؓ(f)它定义一个不同的识别W。你不能单的U它为“name”,因ؓ(f)它会(x)?lt;mailAddress>元素中用的“name”冲H?/P>
另一个问题是DTD的无层次性得理解其中的注解很困难。一个在最上面的注解看h更像是针对全文结构的注解Q但也可能它只是对第一条的注解。最后,DTD不允怽形式上的指定合法域准则,例如寚w政编码域中的5位数限制?/P>
最后,一个DTD使用的语法不同于XMLQ所以它不能被一个标准的XML分析器解析。这意味着你不能将DTD读进DOMQ和~辑、修改它?/P>
Z修补q些~点Q很多的提案已经被提交。像层次性的“概?-schema”,它指定了合法性准则。后面介l了一些主要的提案?/P>
XML概要QSchemaQ?BR>一个大而复杂的标准Q它拥有两部分。一部分指定l构联系Q这是最大最复杂的部分)。另一部分指定XML元素中的内容的合法性机Ӟ可以通过为每个元素指定一个数据类型。一个好消息是,XML概要可以指定M设想的关联。坏消息是他很难实现也很隑֭?fn)?/P>
XML概要的更多的信息Q可以查看W3C specs XML Schema(Structures) and XML Schema(Datatypes).
http://www.w3c.org/XML/Schema.
RELAX NG
XML的规则语a描述Q下一代)--QRegular Language description for XMLQNext GenerationQ)
RELAX NG是一个新兴标准,它要比XMLl构概要单。再不远的将来它也可能成Z个ISO标准?/P>
RELAX NG使用规则表达式来表达l构关系上的限制Q它使用XML概要数据cd机制来表辑ֆ容上的限制。这个标准也使用XML语法Q它包含一个DTD到RELAX的{换器。(说它是“next generation”是因ؓ(f)它是l和TREX 的RELAX概要机制的新版本Q?/P>
关于RELAX NG的更多的信息Q?A >http://www.oasis-open.org/committees/relax-ng/
TREX
针对XML的树(wi)型规则表辑ּQTree Regular Expressions for XMLQ?/P>
它是一个通过为XML文档中的l构和内Ҏ(gu)qC个模版来表达合法性准则的手段。现在作为RELAX NG的一部分?/P>
SOX
面向对象的概要(Schema for Object-oriented XMLQ?/P>
SOX是一个概要提案,它包括扩展数据类型、命名空间和嵌入的文档?/P>
SOX更多的信息:(x)http://www.ascc.net/xml/resource/schematron/schematron.html.
q接和表现标?BR>可以证明QHTML中的文档之间的连接和单的文档格式是最大的优点。下面的标准定位于在XML中保留HTML的好处ƈ增加额外的功能?/P>
XML Linking
q些规范提供一个不同的q接能力Q但对XML的用上形成了一ơ很大的冲击?/P>
XLink
Xlink协议是一个在XML文档间处理连接的规范。这个规范允怸些恰当的改进q接Q包含双向连接、连接到多文档、展开q接、内部指向连接等?/P>
XML 基础
q个标准定义一个XML文档属性,q个属性定义一个“基”地址Q“基”地址在查找一个关联的地址时被使用。(例如Q一个简单的文g名可以在一个基地址目录中被扑ֈQ?/P>
XPointer
一般情况下QXlink规范是将使用它的ID的文档或文档片断作ؓ(f)目标的。XPointer规范定义的机制是针对“在一个XML文档内部l构的寻址”的。XPointer规范不需要文档的作者ؓ(f)一个文档片断定一个ID?/P>
XMLq接的更多的信息Q?A >http://www.w3.org/XML/Linking.
XHTML
XHTML规范是XML文档的一个用途,只不qXML文档更像HTML文档。既然XML文档可以包含L的标识,那么Z么不能定义一个很像HTML标识的XML标识集呢Q这是XHTML的想法。这个规范的l果是一个文档既能在览器中昄Q又能作为XML文档被处理。尽它q不是纯正的XMLQ但是它比HTML更容易被处理?/P>
例如Q在一个格式良好的XML文档中,每一个标识必L一个结束标识。所以在XHTML中,你可能看?lt;p>..</p>Q或<p/>。但你绝对看不到单独?lt;p>?/P>
XHTML规范是一个HTML4.0到XML的再形成。最新的信息在:(x)http://www.w3.org/TR/xhtml1.
知识标准
RDF
资源描述框架QResource Description FrameworkQ?/P>
RDF是一个定义元数据的标准,元数据是描述一个特D的数据条目是什么的信息q指定怎么h使用q个数据条目。例如,联合XHTML规范或HTML面来用,RDF被用来描q页面的内容。例如,如果你的览器存储你的ID信息像FIRSTNAME、LASTNAME和EMAILQ一个RDF描述传输传输个需要NAME和EMAILADDRESS的应用程序相应的信息。想象一下,到那一天,你可能不需要在每个|站里输入你的名字和邮g地址?/P>
关于RDF更多的信息:(x)http://www.w3.org/TR/REC-rdf-syntax
RDF概要
RDF概要允许相容性原则和附加信息的规范?/P>
更多的RDF概要信息Q?A >http://www.w3.org/TR/rdf-schema.
XTM
XML主题映射QXML Topic MapsQ?/P>
在许多方面,M映射标准是一个比RDF更简单的、更Ҏ(gu)使用得知识表C,它更应该值得被关注。迄今ؓ(f)止,RDF是一个W3C标准Q但是,主题映射可能只能作ؓ(f)一U开发者选择的标准?/P>
XML主题映射更多的信息:(x)http://www.topicmaps.org/xtm/index.html.
建立在XML上的标准
下面的标准和提案都是建立在XML之上的。因为XML基本上是一个定义语a的工P所以这些标准用它定义Ҏ(gu)目的标准语言?/P>
扩展文档标准QExtended Document StandardsQ?BR>q些标准定义了用XML产生极端复杂的文档的机制?/P>
SMIL
同步的多媒体l合语言QSynchronized Multimedia Integration LanguageQ?BR>SMIL是一个W3C的标准,它涵盖了音频、视频和动画?/P>
更多关于SMIL的信息:(x)http://www.w3.org/TR/REC-smil.
MathML
数学标记语言QMathematical Markup LanguageQ?/P>
MathML是一个W3C的标准,它处理数学公式的昄?/P>
更多关于MathML的信息:(x)http://www.w3.org/TR/REC-MathML.
SVG
可~的向量囑փQScalable Vector GraphicsQ?/P>
SVG是一个W3C工作草案Q它覆盖了向量图像的昄?/P>
更多关于SVG的信息:(x)http://www.w3.org/TR/WD-SVG.
DrawML
l制元语aQDrawing Meta LanguageQ?/P>
DrawML是一个W3C的附注,它涵盖了技术图表的2D囑փ?/P>
更多的关于DrawML的信息:(x)http://www.w3.org/TR/NOTE-drawml.
?sh)子商务标准QeCommerce StandardsQ?/P>
q些标准定位于在B2B和B2C的范围里使用XML?/P>
ICE
信息和内容交换(Information and Content ExchangeQ?/P>
ICE是一个被内容l营者用的协议。它的焦点在“在传统出版和B2B联系上自动化内容转换和重用?/P>
更多关于ICE的信息:(x)http://www.w3.org/TR/NOTE-ice.
ebXML
ZXML的电(sh)子交易(Electronic Business with XMLQ?/P>
q个标准定位在用XML建立模块化的?sh)子交易框架。它是UN/CEFACT的一个v步品?/P>
更多关于ebXML的信息:(x)http://www.ebxml.org/.
cxml
商业XMLQCommerce XMLQ?/P>
cxml是一个RosettaNetQ?A >www.rosettanet.orgQ标准,它的目的是ؓ(f)了不同的C建立一个在U的名单?/P>
更多关于cxml的信息:(x)http://www.cxml.org/
CBL
通用交易库(Common Business LibraryQ?/P>
CBL是一个元素和属性定义的库?/P>
更多关于CBL的信息:(x)http://www.commerce.net/projects/currentprojects/eco/wg/eCo_Framework_Specifications.html.
UBL
l一商业语言QUniversal Business LanguageQ?/P>
一个OASIS初步定位在编译一个XML交易文档的标准库?/P>
更多关于UBL的信息:(x)http://www.oasis-open.org/committees/ubl.
ȝ
XML是一个正在被q泛的应用的标准Q它正在被用在不同的领域?BR>
原文地址Q?A >http://java.sun.com/developer/EJTechTips/2005/tt1122.html#1
by Greg Murray
作者:(x)格雷|默里
AJAX stands for Asynchronous JavaScript and XML. In essence, AJAX is an efficient way for a web application to handle user interactions with a web page -- a way that reduces the need to do a page refresh or full page reload for every user interaction. This enables rich behavior (similar to that of a desktop application or plugin-based web application) using a browser. AJAX interactions are handled asynchronously in the background. As this happens, a user can continue working with the page. AJAX Interactions are initiated by the JavaScript in the web page. When the AJAX interaction is complete, JavaScript updates the HTML source of the page. The changes are made immediately without requiring a page refresh. AJAX interactions can be used to do things such as validate form entries (while the user is entering them) using server-side logic, retrieve detailed data from the server, dynamically update data on a page, and submit partial forms from the page.
AJAX代表着异步的JAVASCRIPT和XML。本质上QAJAX是一U在WEB应用中通过|页与用户交互的有效方式Q它减少了用户交互中h面或整重载的频率。这样用浏览器可以q行更丰富的动作Q与桌面应用或基于PLUGIN的WEB应用怼Q。AJAX交互在后台异步执行,此时用户可以l箋在这个页面上工作。AJAX是由|页中的JAVASCRIPT驱动的。当AJAX交互完成后,JS更新|页HTML代码。这个动作在不需要刷新页面的情况下迅速执行。AJAX可以用于许多斚wQ例如在用户输入的同时用服务器端规则验证其输入,获得服务器端详细数据q主动更新页面数据,或者提交页面表单的部分数据?BR>What is particularly attractive about this is that AJAX applications do not require a separate plug-in, and are platform and browser-neutral. That said, AJAX is not supported as well in older browsers. Care needs to be taken in writing client-side script that accounts for the differences between browsers. You might consider using a JavaScript library that abstracts the browser differences and in some cases support older browsers using alternative interaction techniques. For more details, see the AJAX FAQ for the Java Developer
是什么让AJAX技术具体如此魅力呢QAJAX应用不需用单独的插gQƈ且是q_和浏览器中立的。也是_(d)AJAXq不被旧的浏览器良好支持。但是不必太q担心,你可以撰写跨不同览器的脚本。你应该考虑使用跨不同浏览器的JS库ƈ且在一些情况下有选择性的使用交互技术以支持旧的览器。了解更多,h看JAVA开发者的AJAX FAQ?A >http://weblogs.java.net/blog/gmurray71/
So Where Does Java Technology Fit In?
那么JAVA技术适合在哪儿用呢Q?BR>Java technology and AJAX work well together. Java technology provides the server-side processing for AJAX interactions. It can provide this through servlets, JavaServer Pages (JSP) technology, JavaServer Faces (JSF) technology, and web services. The programming model for handling AJAX requests uses the same APIs that you would use for conventional web applications. JSF technology can be used to create reusable components that generate the client-side JavaScript and corresponding server-side AJAX processing code. Let's look at an example that uses AJAX and servlets.
JAVA技术与AJAX搭配使用非常不错。JAVA技术ؓ(f)AJAX交互提供服务器端处理Q通过servlets、JavaServer Pages (JSP)、JavaServer Faces (JSF) ?qing)web服务。AJAXh的编E模式用与常规WEB应用相同的API。JSF技术可以用来创建可重用的组Ӟq些lg生成客户端JSq与服务器端AJAX处理代码通信。下面让我们来看一个用AJAX和SERVLETS的例子?BR>Autocomplete Example
实例Q自动完?BR>Imagine a web page in which a user can search for information about an employee. The page includes a field where the user can enter the name of the employee. In this example the entry field has an autocomplete feature. In other words, the user can type in part of the employee name, and the web application attempts to complete the name by listing all employees whose first or last name begins with the characters entered. The autocomplete feature saves the user from having to remember the complete name of the employee or from looking for the name on another page.
假设用户在一个网中搜烦雇员信息。这个页面包含一个输入域Q用户在其中输入雇员的名字。在q个例子中输入域h自动完成的功能。换句话_(d)用户输入雇员名的一部分QW(xu)EB应用通过列出所有姓名以输入字母开头的雇员来帮助完成输入。自动完成功能让用户可以无需C员工的全名或者从另一个页面查扑字。(此句偶之前百思不得其解,后来l永华指点,大约是这L(fng)Q你可以有三U方式查询员工信息,1.C员工的名字?.从别的地方,比如其它面扑ֈ后复制粘贴过来,3.使用自动完成功能Q很昄Q第三种是最省事的,优于其它方式Q所以说3 SAVE FROM 1/2.Q?/P>
Implementing autocomplete in a search field is something that can be performed using AJAX. To do it, you need to provide code on the client and on the server.
可以使用AJAX实现搜烦输入域的自动完成。要实现q个Q需要撰写相应的客户端和服务器端代码?/P>
On the Client
客户?BR>First, the user specifies the URL of a page that is loaded by the browser. For this example let's assume the page is an HTML page that is generated by a JSF component, servlet, or JSP page. The page contains a form text field that has an attribute onkeyup with the name of a JavaScript function doCompletion(). This function is called each time a key is pressed in the form text field.
首先Q用h开一个网c(din)假设这个页面是一个由JSFlg、SERVLET或JSP产生的HTML面。页面中包含一个表单文本域Q它有一个ONKEYUP属性,其gؓ(f)一个JS函数doCompletion()。这个每当文本域有输入改变,q个函数׃(x)被调用?BR> <input type="text"
size="20"
autocomplete="off"
id="complete-field"
name="id"
onkeyup="doCompletion();">
Let's assume that a user types in an "M" character in the form text field. In response, the doCompletion() function is called which, in turn, initializes an XMLHttpRequest object:
假设用户在表单文本域输入字母MQdoCompletion()被调用Q初始化一个XMLHttpRequest对象?BR> function initRequest(url) {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function doCompletion() {
if (completeField.value == "") {
clearTable();
} else {
var url = "autocomplete?action=complete&id=" +
escape(completeField.value);
var req = initRequest(url);
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
parseMessages(req.responseXML);
} else if (req.status == 204){
clearTable();
}
}
};
req.open("GET", url, true);
req.send(null);
}
}
The XMLHttpRequest object is not currently part of standard JavaScript (efforts are underway to standardize it), but is a de facto standard and is the heart of AJAX. This object is responsible for interacting over HTTP with a server-side component (in this case, a servlet).
XMLHttpRequest对象现在q不是JS标准中的一部分Q正在努力将其标准化Q,但它却是事实上的标准q且是AJAX的核心。这个对象对于在HTTP协议上与服务器端lgQ此例中是一个SERVLETQ交互很可靠.
Three parameters are specified when you create an XMLHttpRequest object: a URL, the HTTP method (GET or POST), and whether or not the interaction is asynchronous. In the XMLHttpRequest example, the parameters are:
当创建XMLHttpRequest对象旉指定三个参数Q一个URL,HTTP方式QGET或POSTQ? 交互是否异步。在q个XMLHttpRequest 例子中,q些参数如下Q?BR> * The URL autocomplete, and the text from the complete-field (an M character):
*自动完成的URL和从输入域键入的文字Q?BR> var url = "autocomplete?action=complete&id=" +
escape(completeField.value);
* GET, signifying the HTTP interactions uses the GET method, and true, signifying that the interaction is asynchronous:
*GETQ表CHTTP交互使用GETҎ(gu)QTRUEQ表CZ互是异步的:(x)
req.open("GET", url, true);
A callback function needs to be set when you use asynchronous calls. This callback function is called asynchronously at specific points during HTTP interaction when the readyState property on the XMLHttpRequest changes. In the example the callback function is processRequest(). It's set as the XMLHttpRequest.onreadystatechange property to a function. Notice the call to the parseMessages function when the readState is "4". The XMLHttpRequest.readyState of "4" signifies the successful completion of the HTTP interaction.
当用异步调用时Q需要徏立一个回调函数。HTTP交互中当XMLHttpRequest中的readyState属性改变时Q回调函数被异步调用。此例中回调函数是processRequest()。它Z个函数徏立了一个XMLHttpRequest.onreadystatechange属性。(前两句还不太明白什么意思——译者注Q。注意当readyState?时对parseMessages函数的调用。XMLHttpRequest.readyState?意味着HTTP交互的成功完成?BR>The HTTP interaction begins when XMLHttpRequest.send() is called. If the interaction is asynchronous, the browser continues to process events in the page.
HTTP交互以调用XMLHttpRequest.send()开始。如果交互是异步的,览器前l箋执行面事gQ而不是中断用户当前动作去执行交互动作——译者注Q?BR>On the Server
服务器端
The XMLHttpRequest makes an HTTP GET request to the URL autocomplete, which is mapped to a servlet called AutoComplete. The doGet() method of the AutoComplete servlet is called. Here is what the doGet() method looks like:
XMLHttpRequest动完成的URL产生了一个HTTP GEThQ这个URL被映到一个名为AutoComplete的Servlet上。AutoComplete servlet的doGet() Ҏ(gu)被调用。这里的doGet()Ҏ(gu)如下Q?BR> public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
...
String targetId = request.getParameter("id");
Iterator it = employees.keySet().iterator();
while (it.hasNext()) {
EmployeeBean e = (EmployeeBean)employees.get(
(String)it.next());
if ((e.getFirstName().toLowerCase().startsWith(targetId) ||
e.getLastName().toLowerCase().startsWith(targetId))
&& !targetId.equals("")) {
sb.append("<employee>");
sb.append("<id>" + e.getId() + "</id>");
sb.append("<firstName>" + e.getFirstName() +
"</firstName>");
sb.append("<lastName>" + e.getLastName() +
"</lastName>");
sb.append("</employee>");
namesAdded = true;
}
}
if (namesAdded) {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<employees>" +
sb.toString() + "</employees>");
} else {
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
}
As you can see in this servlet, there is nothing really new you need to learn to write server-side code for AJAX processing. The response content type needs to be set to text/xml for cases where you want to exchange XML documents. With AJAX, you can also exchange plain text or even snippets of JavaScript which may be evaluated or executed by the callback function on the client. Note too that some browsers might cache the results, and so it might be necessary to set the Cache-Control HTTP header to no-cache. In this example, the servlet generates an XML document that contains all employees with a first or last name beginning with the character M. Here is an example of an XML document that is returned to the XMLHttpRequest object that made the call:
如你在SERVLET中所看到Q不需要ؓ(f)写服务器端AJAX处理代码而学?fn)新知识。当你想要发送XML文档Q只需响应内容类型设|ؓ(f)text/xml。用AJAXQ你甚至可以发送普通文本或者小DJS代码Q这些代码可能在客户端被回调函数计算或执行。注意:(x)一些浏览器可能结果缓存,所以有必要讄Cache-Control HTTP header为no-cache。此例中QSERVLET产生一个XML文档Q它包含所有姓或名以M开头的雇员的姓名。下面是一个返回给XMLHttpRequest对象的XML文档例子Q?BR> <employees>
<employee>
<id>3</id>
<firstName>George</firstName>
<lastName>Murphy</lastName>
</employee>
<employee>
<id>2</id>
<firstName>Greg</firstName>
<lastName>Murphy</lastName>
</employee>
<employee>
<id>11</id><firstName>Cindy</firstName>
<lastName>Murphy</lastName>
</employee>
<employee>
<id>4</id>
<firstName>George</firstName>
<lastName>Murray</lastName>
</employee>
<employee>
<id>1</id>
<firstName>Greg</firstName>
<lastName>Murray</lastName>
</employee>
</employees>
Returning to the Client
再来看客L(fng)
When the XMLHttpRequest object that made the initial call receives the response, it calls the parseMessages() function (see the initialization of the XMLHttpRequest earlier in this example for more details). Here is what the parseMessages() function looks like:
当最初发送请求的XMLHttpRequest对象收到回应Q它调用parseMessages() 函数Q参见此例前面XMLHttpRequest的初始化Q。这个函数如下:(x)
function parseMessages(responseXML) {
clearTable();
var employees = responseXML.getElementsByTagName(
"employees")[0];
if (employees.childNodes.length > 0) {
completeTable.setAttribute("bordercolor", "black");
completeTable.setAttribute("border", "1");
} else {
clearTable();
}
for (loop = 0; loop < employees.childNodes.length; loop++) {
var employee = employees.childNodes[loop];
var firstName = employee.getElementsByTagName(
"firstName")[0];
var lastName = employee.getElementsByTagName(
"lastName")[0];
var employeeId = employee.getElementsByTagName(
"id")[0];
appendEmployee(
firstName.childNodes[0].nodeValue,
lastName.childNodes[0].nodeValue,
employeeId.childNodes[0].nodeValue);
}
}
The parseMessages() function receives as a parameter an object representation of the XML document returned by the AutoComplete servlet. The function programmatically traverses the XML document, and then uses the results to update the contents of the HTML page. This is done by injecting into a <div> element whose id is "menu-popup" the HTML source for the names in the XML document:
parseMessages() 函数接收AutoComplete servletq回的XML文档对象做ؓ(f)参数。该函数自动转化XML文档q更新网内容,通过在HTML源文件中为XML文档中的姓名插入一?id ?"menu-popup"的DIV元素Q?BR> <div style="position: absolute;
top:170px;left:140px" id="menu-popup">
As the user enters more characters, the list shortens. The user can then click on one of the names.
当用戯入更多字W,姓名列表变短。用户可以点击要查找的姓名?BR>Hopefully by now you realize that AJAX is simply exchanging information over HTTP in the background of a page, and updating that page dynamically based on the results. For more information about AJAX and Java technology, see the technical article Asynchronous JavaScript Technology and XML (AJAX) With Java 2 Platform, Enterprise Edition. Q?A >http://java.sun.com/developer/technicalArticles/J2EE/AJAX/index.htmlQAlso see the AJAX BluePrints page, Q?A >http://java.sun.com/blueprints/ajax.htmlQand the AJAX FAQ for the Java Developer in Greg Murray's blog. Q?A >http://weblogs.java.net/blog/gmurray71/Q?BR>希望现在你已l了解到AJAX如何在后台简单地交换信息以及(qing)在此基础上动态地更新面。欲了解更多关于AJAX和JAVA技术,可以看这技术文章《Asynchronous JavaScript Technology and XML (AJAX) With Java 2 Platform, Enterprise Edition》(http://java.sun.com/developer/technicalArticles/J2EE/AJAX/index.htmlQ。或者看AJAX蓝图http://java.sun.com/blueprints/ajax.htmlQ或Greg Murray的博客中为JAVA开发者写的AJAX FAQ?A >http://weblogs.java.net/blog/gmurray71/
About the Author
关于作?BR>Greg Murray is the servlet specification lead. Greg is a former member of the Java BluePrints team, and was responsible for the web tier recommendations. He is leading the AJAX effort at Sun with the help of the BluePrints team. Greg has experience with internationalization, web services, J2SE standalone clients, and AJAX-based web clients.
格雷|默里是SERVLET规范领导。他曾是JAVA蓝图工作l会(x)员,非常负责地对WEB TIER提出许多(或者是对XX负责)。在蓝图工作l的协助下他在SUN领导AJAX工作。格h在国际化、WEB服务、J2SE独立客户端和ZAJAX的WEB客户端方面有着丰富的经验?/P>
About the Translater
关于译?BR>Ahdong is wide-interested boy in China.Ahdong is a member of Network Creative Lab of Huaqiao University,and is responsible for the newbees' recommendations about learning.He is leading the software department at the lab with Younghua.Ahdong is interested in and has some experience with Linux,web development with JAVA or PHP,web standard,and AJAX-based web clients.
阿冬是一个兴广泛的中国男孩。他是华侨大学网l创新实验室的一员,负责d对许多初学者提了许多中肯的。他和永华一起领导实验室软g部。阿冬在LINUX、PHP或JAVA WEB开发、WEB标准、基于AJAX的WEB客户端方面有着深厚的兴ƈ多少有一点儿l验?BR>
public void write (OutputStream out) throws IOException public void write (Writer out) throws IOException public void write (Writer out, String encoding) throws IOException |
String name="fancy"; DocumentBuilder parser; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { parser = factory.newDocumentBuilder(); Document doc = parser.parse("user.xml"); Element newlink=doc.createElement(name); doc.getDocumentElement().appendChild(newlink); ((XmlDocument)doc).write(new FileOutputStream(new File("xuser1.xml"))); } catch (Exception e) { //to log it } |
//首先创徏一个DOMSource对象,该构造函数的参数可以是一个Document对象 //doc代表更改后的DOM Tree?BR>DOMSource doms = new DOMSource (doc); //创徏一个File对象,代表DOM Tree所包含的数据的输出介质,q是一个XML文g?BR>File f = new File ("XMLOutput.xml"); //创徏一个StreamResult对象,该构造函数的参数可以取ؓ(f)File对象?BR>StreamResult sr = new StreamResult (f); //下面调用JAXP中的XSLT引擎来实现输出DOM Tree中的数据到XML文g中的功能?BR>//XSLT引擎的输入ؓ(f)DOMSource对象,输出为StreamResut对象?BR>try { //首先创徏一个TransformerFactory对象,再由此创建Transformer对象。Transformer //cȝ当于一个XSLT引擎。通常我们使用它来处理XSL文g,但是在这里我们 //用它来输出XML文档?BR>TransformerFactory tf=TransformerFactory.newInstance(); Transformer t=tf.newTransformer (); //关键的一? 调用Transformer对象 (XSLT引擎)的transform()Ҏ(gu),该方法的W一 //个参数是DOMSource对象,W二个参数是StreamResult对象?BR>t.transform(doms,sr); } catch (TransformerConfigurationException tce) { System.out.println("Transformer Configuration Exception\n-----"); tce.printStackTrace(); } catch (TransformerException te) { System.out.println ("Transformer Exception\n---------"); te.printStackTrace (); } |
//首先创徏一个TransformerFactory对象,再由此创建Transformer对象?BR>TransformerFactory tf=TransformerFactory.newInstance(); Transformer t=tf.newTransformer (); //获取Transformser对象的输出属?亦即XSLT引擎的缺省输出属?q是一?BR>//java.util.Properties对象?BR>Properties properties = t.getOutputProperties(); //讄新的输出属?输出字符~码为GB2312,q样可以支持中文字符,XSLT引擎所输出 //的XML文档如果包含了中文字W?可以正常昄,不会(x)出现所谓的"汉字问题"?BR>//L(fng)意OutputKeyscȝ字符串常数OutputKeys.ENCODING?BR>properties.setProperty(OutputKeys.ENCODING,"GB2312"); /更新XSLT引擎的输出属性?BR>t.setOutputProperties(properties); //调用XSLT引擎,按照输出属性中的设|?输出DOM Tree中的内容到输Z质中?BR>t.transform(DOMSource_Object,StreamResult_Object); |
public static final java.lang.String METHOD |
public static final java.lang.String VERSION |
public static final java.lang.String ENCODING |
public static final java.lang.String OMIT_XML_DECLARATION |
Q?xml version="1.0" standalone="yes" encoding="utf-8" ?Q? |
public static final java.lang.String INDENT |
public static final java.lang.String MEDIA_TYPE |
Properties properties = transformer.getOutputProperties(); |
properties.setProperty(OutputKeys.ENCODING,"GB2312"); properties.setProperty(OutputKeys.METHOD,"html"); properties.setProperty(OutputKeys.VERSION,"4.0"); ……………………………………………………? |
//首先创徏一个DOMSource对象,该构造函数的参数可以是一个Document对象 //doc代表更改后的DOM Tree?BR>DOMSource domSource = new DOMSource (doc); //创徏一个DOMResult对象,临时保存XSLT引擎的输出结果?BR>DOMResult domResult = new DOMResult(); //下面调用JAXP中的XSLT引擎来实现输出DOM Tree中的数据到XML文g中的功能?BR>//XSLT引擎的输入ؓ(f)DOMSource对象,输出为DOMResut对象?BR>try { //首先创徏一个TransformerFactory对象,再由此创建Transformer对象。Transformer //cȝ当于一个XSLT引擎。通常我们使用它来处理XSL文g,但是在这里我们 //用它来输出XML文档?BR>TransformerFactory tf=TransformerFactory.newInstance(); Transformer t=tf.newTransformer (); //讄XSLT引擎的属?必不可少,否则?x)?汉字问题")?BR>Properties properties = t.getOutputProperties(); properties.setProperty(OutputKeys.ENCODING,"GB2312"); t.setOutputProperties(properties); //关键的一? 调用Transformer对象 (XSLT引擎)的transform()Ҏ(gu),该方法的W一 //个参数是DOMSource对象,W二个参数是DOMResult对象?BR>t.transform(domSource,domResult); //创徏~省的Xalan XML Serializer,使用它将临时存放在DOMResult对象 //(domResult)中的内容以输出流的Ş式输出到输出介质中?BR>Serializer serializer = SerializerFactory.getSerializer (OutputProperties.getDefaultMethodProperties("xml")); //讄Xalan XML Serializer的输出属?q一步必不可?否则也可能?BR>//所谓的"汉字问题"?BR>Properties prop=serializer.getOutputFormat(); prop.setProperty("encoding","GB2312"); serializer.setOutputFormat(prop); //创徏一个File对象,代表DOM Tree所包含的数据的输出介质,q是一个XML文g?BR>File f = new File ("xuser3.xml"); //创徏文g输出对象fos,L(fng)意构造函数的参数?BR>FileOutputStream fos=new FileOutputStream(f); //讄Xalan XML Serializer的输出流?BR>serializer.setOutputStream(fos); //串行化输出结果?BR>serializer.asDOMSerializer().serialize(domResult.getNode()); } catch (Exception tce) { tce.printStackTrace(); } |
代码: |
public interface IOrderService { public abstract Order saveNewOrder(Order order) throws OrderException, OrderMinimumAmountException; public abstract List findOrderByUser( String user) throws OrderException; public abstract Order findOrderById(int id) throws OrderException; public abstract void setOrderDAO( IOrderDAO orderDAO); } |
代码: |
public interface IOrderDAO { public abstract Order findOrderById( final int id); public abstract List findOrdersPlaceByUser( final String placedBy); public abstract Order saveOrder( final Order order); } |
代码: |
<bean id="mySessionFactory" class="org.springframework.orm.hibernate. LocalSessionFactoryBean"> <property name="mappingResources"> <list> <value> com/meagle/bo/Order.hbm.xml </value> <value> com/meagle/bo/OrderLineItem.hbm.xml </value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> net.sf.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql"> false </prop> <prop key="hibernate.proxool.xml"> C:/MyWebApps/.../WEB-INF/proxool.xml </prop> <prop key="hibernate.proxool.pool_alias"> spring </prop> </props> </property> </bean> <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) --> <bean id="myTransactionManager" class="org. springframework. orm. hibernate. HibernateTransactionManager"> <property name="sessionFactory"> <ref local="mySessionFactory"/> </property> </bean> |
代码: |
<!-- ORDER SERVICE --> <bean id="orderService" class="org. springframework. transaction. interceptor. TransactionProxyFactoryBean"> <property name="transactionManager"> <ref local="myTransactionManager"/> </property> <property name="target"> <ref local="orderTarget"/> </property> <property name="transactionAttributes"> <props> <prop key="find*"> PROPAGATION_REQUIRED,readOnly,-OrderException </prop> <prop key="save*"> PROPAGATION_REQUIRED,-OrderException </prop> </props> </property> </bean> <!-- ORDER TARGET PRIMARY BUSINESS OBJECT: Hibernate implementation --> <bean id="orderTarget" class="com. meagle. service. spring. OrderServiceSpringImpl"> <property name="orderDAO"> <ref local="orderDAO"/> </property> </bean> <!-- ORDER DAO OBJECT --> <bean id="orderDAO" class="com. meagle. service. dao. hibernate. OrderHibernateDAO"> <property name="sessionFactory"> <ref local="mySessionFactory"/> </property> </bean> |
代码: |
public abstract class BaseAction extends Action { private IOrderService orderService; public void setServlet(ActionServlet actionServlet) { super.setServlet(actionServlet); ServletContext servletContext = actionServlet.getServletContext(); WebApplicationContext wac = WebApplicationContextUtils. getRequiredWebApplicationContext( servletContext); this.orderService = (IOrderService) wac.getBean("orderService"); } protected IOrderService getOrderService() { return orderService; } } |
代码: |
struts-config.xml file. <action path="/SaveNewOrder" type="com.meagle.action.SaveOrderAction" name="OrderForm" scope="request" validate="true" input="/NewOrder.jsp"> <display-name>Save New Order</display-name> <exception key="error.order.save" path="/NewOrder.jsp" scope="request" type="com.meagle.exception.OrderException"/> <exception key="error.order.not.enough.money" path="/NewOrder.jsp" scope="request" type="com. meagle. exception. OrderMinimumAmountException"/> <forward name="success" path="/ViewOrder.jsp"/> <forward name="failure" path="/NewOrder.jsp"/> </action> |
代码: |
public ActionForward execute( ActionMapping mapping, ActionForm form, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws java.lang.Exception { OrderForm oForm = (OrderForm) form; // Use the form to build an Order object that // can be saved in the persistence layer. // See the full source code in the sample app. // Obtain the wired business service object // from the service locator configuration // in BaseAction. // Delegate the save to the service layer and // further upstream to save the Order object. getOrderService().saveNewOrder(order); oForm.setOrder(order); ActionMessages messages = new ActionMessages(); messages.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "message.order.saved.successfully")); saveMessages(request, messages); return mapping.findForward("success"); } |