TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
在当今――Web 2.0概念铺天盖地的Internet环境下,简易的AJAX集成对于一个成功的WEB框架来说是不可或缺的。因此,Struts 2其中的一个重要的功能(Feature)就是“First-class AJAX support - Add interactivity and flexibility with AJAX tags that look and feel just like standard Struts tags(大意:一流的AJAX支持――通过AJAX标志增加互动性和灵活性,而且使用这些AJAX标志与普通的Struts标志同样简单)”。 实现原理 基于不重新发明轮子的原则,Struts 2并没有开发新的AJAX框架,而是使用时下java EE平台中比较流行的AJAX框架――Dojo和DWR。 最近在Musachy Barroso等同志的无私奉献下,开发了Struts 2的JSON插件(Plugin),极大地方便了我们输出JSON结果(Result)。
JSON插件(Plugin) 在Struts 2的showcase中的AJAX部分,JSON的结果输出是通过Freemaker模板实现。这种方法在简易性和灵活性上都比不上JSON插件,所以JSON插件值得向大家五星推荐。 下面让我们看一个JSON插件的例子。 首先到以下网址http://code.google.com/p/jsonplugin/downloads/list下载JSON插件的JAR包,并将其加入你的WebContentWEB-INFlib下。 接下是本例子的Action代码:

package
tutorial;


import
java.util.ArrayList;

import
java.util.List;


import
com.Googlecode.jsonplugin.annotations.JSON;

import
com.opensymphony.xwork2.ActionSupport;

 
public
class
JsonPluginAction
extends
ActionSupport

{
private static final long serialVersionUID = -6784977600668791997L;
private int bookId;
private String title;
private double price;
private List<String> comments;
private transient String secret1;
private String secret2;

@JSON(name="ISBN")
 public int getBookId() {
return bookId;
}

 public void setBookId(int bookId) {
this.bookId = bookId;
}

 public List<String> getComments() {
return comments;
}

 public void setComments(List<String> comments) {
this.comments = comments;
}

 public double getPrice() {
return price;
}

 public void setPrice(double price) {
this.price = price;
}

 public String getTitle() {
return title;
}
 public void setTitle(String title) {
this.title = title;
}

@Override
 public String execute() {
bookId = 15645912;
title = "Max On Java";
price = 0.9999d;
comments = new ArrayList<String>(3);
comments.add("It"s no bad!");
comments.add("WOW!");
comments.add("No comment!");
secret1 = "You can"t see me!";
secret2 = "I am invisible!";
return SUCCESS;
}
}
清单1 src/tutorial/JsonPluginAction.java 以上代码值得注意的是,通过@JSON的JAVA注释(Annotation),我们可以改变JSON结果的属性名称,另外带有transient修饰符与没有Getter方法的字段(field)都不会被串行化为JSON。 然后,我们来配置一下此Action,代码如下:
<?
xml version="1.0" encoding="UTF-8"
?>
<!
DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"
>
<
struts
>
<
package
name
="Struts2_AJAX_DEMO"
extends
="json-default"
>
<
action
name
="JsonPlugin"
class
="tutorial.JsonPluginAction"
>
<
result
type
="json"
/>
</
action
>
</
package
>
</
struts
>
清单2 src/struts.xml 上面配置文件的“package”元素和以往不同的是,它扩展了“json-default”而不是“struts-default”。“json-default”是在jsonplugin-0.11.jar包里的struts-plugin.xml中定义的。该文件同时定义了“json”的结果类型,有兴趣的朋友可以打开此文件看看。 发布运行应用程序,在浏览器中键入:http://localhost:8080/Struts2_Ajax/JsonPlugin.action,出现下载文件对话框,原因是JSON插件将HTTP响应(Response)的MIME类型设为“application/json”。把文件下载下来,用记事本打开,内容如下:
{
"
ISBN
"
:
15645912
,
"
comments
"
:[
"
It"s no bad!
"
,
"
WOW!
"
,
"
No comment!
"
],
"
price
"
:
0.9999
,
"
title
"
:
"
Max On Java
"
}
清单3 例子1输出的JSON串 当然这还不是一个完整的AJAX的例子,下面让我们写一个HTML文件将其完成,HTML代码如下:
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<
html
xmlns
="http://www.w3.org/1999/xhtml"
>
<
head
>
<
title
>
JSON Plugin
</
title
>
<
script
type
="text/javascript"
>
var
bXmlHttpSupport
=
(
typeof
XMLHttpRequest
!=
"
undefined
"
||
window.ActiveXObject);
if
(
typeof
XMLHttpRequest
==
"
undefined
"
&&
window.ActiveXObject) {
function
XMLHttpRequest() {
var
arrSignatures
=
[
"
MSXML2.XMLHTTP.5.0
"
,
"
MSXML2.XMLHTTP.4.0
"
,
"
MSXML2.XMLHTTP.3.0
"
,
"
MSXML2.XMLHTTP
"
,
"
Microsoft.XMLHTTP
"
];
for
(
var
i
=
0
; i
<
arrSignatures.length; i
++
) {
try
{
var
oRequest
=
new
ActiveXObject(arrSignatures);
return
oRequest;
}
catch
(oError) {
/*
ignore
*/
}
}
throw
new
Error(
"
MSXML is not installed on your system.
"
);
}
}
function
retrieveBook() {
if
(bXmlHttpSupport) {
var
sUrl
=
"JsonPlugin.action";
var
oRequest
=
new
XMLHttpRequest();
oRequest.onreadystatechange
=
function
() {
if
(oRequest.readyState
==
4
) {
var
oBook
=
eval("("
+
oRequest.responseText
+
")");
var
bookHolder
=
document.getElementById("bookHolder");
var
sBook
=
"
<
p
><
b
>
ISBN:
</
b
>
"
+
oBook.ISBN
+
"
</
p
>
";
sBook
+=
("
<
p
><
b
>
Title:
</
b
>
"
+
oBook.title
+
"
</
p
>
");
sBook
+=
("
<
p
><
b
>
Price:
</
b
>
$"
+
oBook.price
+
"
</
p
>
");
sBook
+=
("
<
b
><
i
>
Comments:
</
i
></
b
><
hr
/>
");
for
(i
=
0
; i
<
oBook.comments.length; i
++
) {
sBook
+=
("
<
p
><
b
>
#"
+
(i
+
1
)
+
"
</
b
>
"
+
oBook.comments
+
"
</
p
>
");
}
bookHolder.innerHTML
=
sBook;
}
};
oRequest.open("POST", sUrl);
oRequest.send(
null
);
}
}
</
script
>
</
head
>
<
body
>
<
input
type
="button"
value
="Retrieve Book"
onclick
="retrieveBook()"
/>
<
div
id
="bookHolder"
></
div
>
</
body
>
</
html
>
清单4 WebContent/JsonPlugin.html 以上代码中,我没有使用任何的AJAX的Javascript包,而是参考《Professional Javascript For Web Developer》手工创建XHR(XMLHttpRequest),并在XHR完成后使用eval()方法将JSON字符串变为JSON对象。需要注意的是,要调用eval函数时,必须使用“(”和“)”将JSON字符串括起来,否则会出错的。 打开http://localhost:8080/Struts2_Ajax/JsonPlugin.html,点击“Retrieve Book”按钮,页面如下图所示: 
图1 JsonPlugin.html页面输出 Struts 2与Dojo Dojo是开源Javascript工具包,它引了Widget的概念,方便了Javascript面向对象编程(OOP),改进Javascript的事件模型。在此我不打算对此进行深入的讲解,有兴趣的朋友的可以找网上找一些关于Dojo的资料学习。 Struts 2基于Dojo编写一些AJAX标志(在Dojo中称为Widget),要使用这些标志的AJAX功能,需要将标志的“theme”属性设为“ajax”。同时,亦需要将加入在<head>与</head>之间加入<s:head theme="ajax" />。当使用这些标志的AJAX功能,有些属性可能会经常用到,所以我会对这些属性稍作解释。
名称
描述
href
XHR(XMLHttpRequest)请求的地址
listenTopics
监听的Dojo话题(Topic)以触发自身,如可以在可以通过发布(Publish)相应的话题,通知<s:autocompleter />重新加载其备选项(Options)
notifyTopics
完成远程调用后,发出通知,触发相应的Javascript函数或Dojo Widget
formId
需要提交到服务器的表单的ID
formFilter
过滤表单字段的Javascript函数名称
indicator
在XHR处理过程中,包含用户提示的信息的HTML元素的ID,如图片或DIV等
表1 常用的AJAX标志属性 这些标志包括:<s:a />、<s: submit />、<s:autocompleter />和<s:tree />等,下面我将分别讲解。 1、<s:a />和<s:submit /> 这两个标志方便了我们的调用XHR实现AJAX,所以上面的HTML如果使用了这两标志将会变得更简单,因为我们不用再去理会繁锁的XHR创建和设定的工作。下面是示例代码:
<%
@ page language
=
"
java
"
contentType
=
"
text/html; charset=utf-8
"
pageEncoding
=
"
utf-8
"
%>
<%
@ taglib prefix
=
"
s
"
uri
=
"
/struts-tags
"
%>
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<
html
xmlns
="http://www.w3.org/1999/xhtml"
>
<
head
>
<
title
>
JSON Plugin
</
title
>
<
s:head
theme
="ajax"
/>
<
script
type
="text/javascript"
>
dojo.addOnLoad(
function
() {
dojo.event.topic.subscribe("retrieveBook",
this
,
function
(data, type, e){
if
(type
==
"load") {
showBook(data);
}
else
if
(type
==
"error") {
alert("Can not retrieve the book");
}
});
});
function
showBook(strBook) {
var
oBook
=
eval("("
+
strBook
+
")");
var
bookHolder
=
document.getElementById("bookHolder");
var
sBook
=
"
<
p
><
b
>
ISBN:
</
b
>
"
+
oBook.ISBN
+
"
</
p
>
";
sBook
+=
("
<
p
><
b
>
Title:
</
b
>
"
+
oBook.title
+
"
</
p
>
");
sBook
+=
("
<
p
><
b
>
Price:
</
b
>
$"
+
oBook.price
+
"
</
p
>
");
sBook
+=
("
<
b
><
i
>
Comments:
</
i
></
b
><
hr
/>
");
for
(i
=
0
; i
<
oBook.comments.length; i
++
) {
sBook
+=
("
<
p
><
b
>
#"
+
(i
+
1
)
+
"
</
b
>
"
+
oBook.comments
+
"
</
p
>
");
}
bookHolder.innerHTML
=
sBook;
}
</
script
>
</
head
>
<
body
>
<
s:url
id
="bookUrl"
value
="/JsonPlugin.action"
/>
<
s:submit
href
="%{bookUrl}"
theme
="ajax"
indicator
="indicator"
value
="Retrieve Book"
align
="left"
notifyTopics
="retrieveBook"
/>
<
s:a
theme
="ajax"
href
="%{bookUrl}"
indicator
="indicator"
notifyTopics
="retrieveBook"
>
Retrieve Book
</
s:a
>
<
img
id
="indicator"
src
="/cwbwebhome/images/indicator.gif"
alt
="Loading "
style
="display:none"
/>
<
div
id
="bookHolder"
></
div
>
</
body
>
</
html
>
清单5 WebContent/LinkButton.jsp 可能上述代码还不够简洁,因为我将HTML格式化的工作都放在Javascript中完成。但如果你的XHR返回的是HTML片段,你可以简单地将<s:a />或<s:submit />的“targets”属性设为“bookHolder”即可,详情大家可以参考Struts 2 Showcase。至于返回HTML片段,可以通过Action + Freemaker完成。 2、<s:autocompleter /> Autocomplete是比较经典的AJAX应用,虽然谷歌已经停止使用这一功能,但就Autocompleter自身而言的确是很酷的。下面是一个<s:autocompleter />的例子。 首先,我要伪造一些字符串数据,代码如下:

package
tutorial;


import
java.util.ArrayList;

import
java.util.List;

 
public
final
class
Datas

{
public static final List<String> NAMES;
 static {
NAMES = new ArrayList<String>();
NAMES.add("Alabama");
NAMES.add("Alaska");
NAMES.add("American Samoa");
NAMES.add("Arizona");
NAMES.add("Arkansas");
NAMES.add("Armed Forces Europe");
NAMES.add("Armed Forces Pacific");
NAMES.add("Armed Forces the Americas");
NAMES.add("California");
NAMES.add("Colorado");
NAMES.add("Connecticut");
NAMES.add("Delaware");
NAMES.add("District of Columbia");
NAMES.add("Federated States of Micronesia");
NAMES.add("Florida");
NAMES.add("Georgia");
NAMES.add("Guam");
NAMES.add("Hawaii");
NAMES.add("Idaho");
NAMES.add("Illinois");
NAMES.add("Indiana");
NAMES.add("Iowa");
NAMES.add("Kansas");
NAMES.add("Kentucky");
NAMES.add("Louisiana");
NAMES.add("Maine");
NAMES.add("Marshall Islands");
NAMES.add("Maryland");
NAMES.add("Massachusetts");
NAMES.add("Michigan");
NAMES.add("Minnesota");
NAMES.add("Mississippi");
NAMES.add("Missouri");
NAMES.add("Montana");
NAMES.add("Nebraska");
NAMES.add("Nevada");
NAMES.add("New Hampshire");
NAMES.add("New Jersey");
NAMES.add("New Mexico");
NAMES.add("New York");
NAMES.add("North Carolina");
NAMES.add("North Dakota");
NAMES.add("Northern Mariana Islands");
NAMES.add("Ohio");
NAMES.add("Oklahoma");
NAMES.add("Oregon");
NAMES.add("Pennsylvania");
NAMES.add("Puerto Rico");
NAMES.add("Rhode Island");
NAMES.add("South Carolina");
NAMES.add("South Dakota");
NAMES.add("Tennessee");
NAMES.add("Texas");
NAMES.add("Utah");
NAMES.add("Vermont");
NAMES.add("Virgin Islands, U.S.");
NAMES.add("Virginia");
NAMES.add("Washington");
NAMES.add("West Virginia");
NAMES.add("Wisconsin");
NAMES.add("Wyoming");
}
}
清单6 src/tutorial/Datas.java 然后是用于获取和过滤数据的Action,代码如下:

package
tutorial;


import
java.util.ArrayList;

import
java.util.List;


import
com.opensymphony.xwork2.ActionSupport;

 
public
class
AutocompleterAction
extends
ActionSupport

{
private static final long serialVersionUID = -8201401726773589361L;
private List<String[]> names;
private String start;
 public void setStart(String start) {
this.start = start;
}
 public List<String[]> getNames() {
return names;
}

@Override
 public String execute() {
names = new ArrayList<String[]>();
 if(start == null || "".equals(start.trim())) {
start = "a";
}
 for(String s : Datas.NAMES) {
 if(s.toLowerCase().startsWith(start.toLowerCase())) {
 names.add(new String[] { s, s });
}
}
return SUCCESS;
}
}
清单7 src/tutorial/AutocmpleterAction.java 上述Action会以JSON的形式返回以start开头的Datas.NAMES的中字符串,以下是此Action的配置:
<
action
name
="Autocompleter"
class
="tutorial.AutocompleterAction"
>
<
result
type
="json"
>
<
param
name
="root"
>
names
</
param
>
</
result
>
</
action
>
清单8 Autocompleter Action的配置代码片段 在JSON类型结果的参数中加入“root”参数可以设定输出JSON结果的根,以上述情况为例,如果没有“root”参数,输出将为“{ "names": [ ["xxx", "xxx"]...] }”,加了之后变就会成“[ ["xxx", "xxx"]...] ”。接下来,让我们看看页面的代码:
<%
@ page language
=
"
java
"
contentType
=
"
text/html; charset=utf-8
"
pageEncoding
=
"
utf-8
"
%>
<%
@ taglib prefix
=
"
s
"
uri
=
"
/struts-tags
"
%>
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<
html
xmlns
="http://www.w3.org/1999/xhtml"
>
<
head
>
<
title
>
Struts 2 AJAX - Autocompleter
</
title
>
<
s:head
theme
="ajax"
/>
</
head
>
<
body
>
<
h2
>
Autocompleter
</
h2
>
<
s:form
action
="autocompleterForm"
>
<
s:textfield
label
="abc"
name
="abc"
/>
<
tr
>
<
td
class
="tdLabel"
>
<
label
class
="label"
>
No AJAX Autocompleter:
</
label
>
</
td
>
<
td
>
<
s:autocompleter
theme
="simple"
name
="user"
list
="@tutorial.Datas@NAMES"
/>
</
td
>
</
tr
>
<
tr
>
<
td
class
="tdLabel"
>
<
label
class
="label"
>
AJAX Autocompleter:
</
label
>
</
td
>
<
td
>
<
s:url
id
="dataUrl"
value
="/Autocompleter.action"
/>
<
s:autocompleter
theme
="ajax"
name
="start"
href
="%{dataUrl}"
loadOnTextChange
="true"
loadMinimumCount
="1"
indicator
="indicator"
autoComplete
="false"
showDownArrow
="false"
/>
<
img
id
="indicator"
src
="/cwbwebhome/images/indicator.gif"
alt
="Loading "
style
="display:none"
/>
</
td
>
</
tr
>
</
s:form
>
</
body
>
</
html
>
清单9 WebContent/Autocompleter.jsp 上述页面包含两个<s:autocompleter />标志,前者使用“simple”模板,所以不具有AJAX功能,它的数据将以HTML方式输出到最终页面里;而后者则使用了“ajax”模板,每当输入框的值发生改变时,它都向URL“/Autocompleter.action”发送请求,Action根据请求中的start参数的值,返回相当的JSON,在请求完成后页面通过回调函数改变输入框的下拉提示,效果如下图所示:
图2 Autocompleter.jsp页面输出 3、<s:tree /> 树是是比较常用的数据结构,因为它可以很好地体现真实世界中对象之间的关系。<s:tree />的使用也相对简单,但需要说明的是――Struts 2.0.6 GA版本的<s:tree />是有BUG的,大家可以点击这个链接https://issues.apache.org/struts/browse/WW-1813了解详细的情况。这个BUG主要是在<s:tree />的通过“treeCollapsedTopic”、“treeExpandedTopic”和“treeSelectedTopic”设定的话题(Topic)都没有起作用,上述链接相应给出了解决方法,但我认为该方法太麻烦(需要自己重新编译和打包Struts 2),所以下面的例子,我将另辟?芯叮?请参考以下代码。
<%
@ page language
=
"
java
"
contentType
=
"
text/html; charset=utf-8
"
pageEncoding
=
"
utf-8
"
%>
<%
@ taglib prefix
=
"
s
"
uri
=
"
/struts-tags
"
%>
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<
html
xmlns
="http://www.w3.org/1999/xhtml"
>
<
head
>
<
title
>
Struts 2 AJAX - Tree
</
title
>
<
s:head
theme
="ajax"
debug
="true"
/>
<
script
type
="text/javascript"
>
function
treeNodeSelected(arg) {
alert(arg.source.title
+
" selected");
}
dojo.addOnLoad(
function
() {
var
s
=
dojo.widget.byId("parentId").selector;
dojo.event.connect(s, "select", "treeNodeSelected");
});
</
script
>
</
head
>
<
body
>
<
h2
>
Tree
</
h2
>
<
div
style
="float:left; margin-right: 50px;"
>
<
s:tree
label
="parent"
id
="parentId"
theme
="ajax"
templateCssPath
="/struts/tree.css"
showRootGrid
="true"
showGrid
="true"
>
<
s:treenode
theme
="ajax"
label
="child1"
id
="child1Id"
>
<
s:treenode
theme
="ajax"
label
="grandchild1"
id
="grandchild1Id"
/>
<
s:treenode
theme
="ajax"
label
="grandchild2"
id
="grandchild2Id"
/>
<
s:treenode
theme
="ajax"
label
="grandchild3"
id
="grandchild3Id"
/>
</
s:treenode
>
<
s:treenode
theme
="ajax"
label
="child2"
id
="child2Id"
/>
<
s:treenode
theme
="ajax"
label
="child3"
id
="child3Id"
/>
<
s:treenode
theme
="ajax"
label
="child4"
id
="child4Id"
/>
<
s:treenode
theme
="ajax"
label
="child5"
id
="child5Id"
>
<
s:treenode
theme
="ajax"
label
="gChild1"
id
="gChild1Id"
/>
<
s:treenode
theme
="ajax"
label
="gChild2"
id
="gChild2Id"
/>
</
s:treenode
>
</
s:tree
>
</
div
>
</
body
>
</
html
>
清单10 WebContent/Tree.jsp 因为Dojo的树控件,即使在没有设定“selector”情况下,也会自动生成一个默认的Selector,所以只要将其事件绑定到特定的事件处理函数即可。 打开http://localhost:8080/Struts2_Ajax/Tree.jsp,点击任一树节点,页面如下图所示:
图3 Tree.jsp页面输出 总结 我原本打算用一篇文章写完这个“Struts 2与AJAX”。不过在写的过程中,发现内容越来越多。如果勉强写成一篇,朋友们读起来也会很麻烦,所以我决定分开几部分,本文为第一部分。 另外,之前有的朋友建议我建一个Google的讨论组,方便大家讨论问题。我觉得这个提议非常好,一直以来都是“一人写,大家留言”,这种相对单向的方式不免有所欠缺,而且本人所知也有限,开个讨论组大家可以相互讨论,共同进步。 因为Struts2已经被创建,所以申请了“struts2cn”,有兴趣的朋友,欢迎加入。
|
|