Struts2与AJAX的相关概念以及使用Struts_Dojo插件
Struts2与AJAX(第一部分)
2009-05-08 08:40 by 墙头草, 749 visits,?网摘,?收藏,?编辑
在当今——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插件的例子。
首先到以下网址/p/jsonplugin/downloads/list下载JSON插件的JAR包,并将其加入你的WebContent\WEB-INF\lib下。
接下是本例子的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?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?getComments()?{? ? ? ?return?comments;? ?}? ?public?void?setComments(List?comments)?{? ? ? ?ments?=?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?=? ? ? ?title?=?"Max On Java";? ? ? ?price?=?0.9999d;? ? ? ?comments?=?new?ArrayList(3);? ? ? ?comments.add("It's no bad!");? ? ? ?comments.a