在Struts 2中使用JSON Ajax支持

来源:互联网 发布:德章泰穆雷体测数据 编辑:程序博客网 时间:2024/05/16 05:03

JSON插件提供了一种名为json的ResultType,一旦为某个Action指定了一个类型为json的Result,则该Result无需映射到任何视图资源。因为JSON插件会负责将Action里的状态信息序列化成JSON格式的数据,并将该数据返回给客户端页面的JavaScript。

  简单地说,JSON插件允许我们在JavaScript中异步调用Action,而且Action不再需要使用视图资源来显示该Action里的状态信息,而是由JSON插件负责将Action里的状态信息返回给调用页面——通过这种方式,就可以完成Ajax交互。

  Struts2提供了一种可插拔方式来管理插件,安装Struts2的JSON插件与安装普通插件并没有太大的区别,一样只需要将Struts2插件的JAR文件复制到Web应用的WEB-INF/lib路径下即可。

  安装JSON插件按如下步骤进行:

  (1)登陆http://code.google.com/p/jsonplugin/downloads/list站点,下载Struts2的JSON插件的最新版本,当前最新版本是0.7,我们可以下载该版本的JSON插件。

  (2)将下载到的jsonplugin-0.7.jar文件复制到Web应用的WEB-INF路径下,即可完成JSON插件的安装。

  实现Actio逻辑

  假设wo,en输入页面中包含了三个表单域,这三个表单域对于三个请求参数,因此应该使用Action来封装这三个请求参数。三个表单域的name分别为field1、field2和field3。

  处理该请求的Action类代码如下:   public class JSONExample
  {
  //封装请求参数的三个属性
  private String field1;
  private transient String field2;
  private String field3;
  //封装处理结果的属性
  private int[] ints = {10, 20};
  private Map map = new HashMap();
  private String customName = "custom";
  //三个请求参数对应的setter和getter方法
  public String getField1()
  {
  return field1;
  }
  public void setField1(String field1)
  {
  this.field1 = field1;
  }
  //此处省略了field1和field2两个字段的setter和getter方法
  ...
  //封装处理结果的属性的setter和getter方法
  public int[] getInts()
  {
  return ints;
  }
  public void setInts(int[] ints)
  {
  this.ints = ints;
  }
  public Map getMap()
  {
  return map;
  }
  public void setMap(Map map)
  {
  this.map = map;
  }
  //使用注释语法来改变该属性序列化后的属性名
  @JSON(name="newName")
  public String getCustomName()
  {
  return this.customName;
  }
  public String execute()
  {
  map.put("name", "yeeku");
  return Action.SUCCESS;
  }
  }  在上面代码中,使用了JSON注释,注释时指定了name域,name域指定Action属性被序列化成JSON对象的属性名。除此之外,JSON注释还支持如下几个域:

 

  

 

      serialize:设置是否序列化该属性

  deserialize:设置是否反序列化该属性。

  format:设置用于格式化输出、解析日期表单域的格式。例如"yyyy-MM-dd'T'HH:mm:ss"。

  配置该Action与配置普通Action存在小小的区别,应该为该Action配置类型为json的Result。而这个Result无需配置任何视图资源。

  配置该Action的struts.xml文件代码如下:  <?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.i18n.encoding" value="UTF-8"/>
<package name="example" extends="json-default">
<action name="JSONExample" class="lee.JSONExample">
<result type="json"/>
</action>
</package>
</struts>    在上面配置文件中有两个值得注意的地方:

  第一个地方是配置struts.i18n.encoding常量时,不再是使用GBK编码,而是UTF-8编码,这是因为Ajax的POST请求都是以UTF-8的方式进行编码的。

  第二个地方是配置包时,自己的包继承了json-default包,而不再继承默认的default包,这是因为只有在该包下才有json类型的Result。

 

 

 

页面操作。Jquery中已经提供几供ajax请求的方法,如果返回的是json对象,使用jQuery.getJSON(url,[data],[callback])会比较方便,

 
jQuery.getJSON(url,[data],[callback]) 通过 HTTP GET 请求载入 JSON 数据。
 
返回值
XMLHttpRequest
 
参数
url (String) : 发送请求地址。
data (Map) : (可选) 待发送 Key/value 参数。
callback (Function) : (可选) 载入成功时回调函数。
 
参数部分浏览器的缓存是以url为标识的,如果url相同会使用缓存中的数据,如果不想使用缓存,可以在参数中加入一个随机数。
 
jQuery.each(obj,callback)
通用例遍方法,可用于例遍对象和数组
参数
object (Object) : 需要例遍的对象或数组。
callback (Function) : (可选) 每个成员/元素执行的回调函数。
回调函数拥有两个参数:第一个为对象的成员或数组的索引,第二个为对应变量或内容。
Jquery操作下拉列表添加选项的方法为: $(“# categoryId”)[0].options.add(option);
 
页面代码如下(部分):
<. language="." type="text/." src="/.s/jquery-1.2.2.js"></.>
<. language=".">
       function fillChannel(id){
              var url = "/book/getAjaxBookChannelList.action";
              $.getJSON(url,{ran:Math.random()},function(json){
                     if(json.strAjaxChannel.length > 0){
                            var obj = .('(' + json.strAjaxChannel + ')');
                            $.each(obj,function(i,n){
                          option = new Option(n,i);
                          if(i==id)option.selected=true;
                         document.getElementById("channellistId").options.add(option);
                      });
                      option = new Option("全部频道",999);
                      if(id == 999)option.selected=true;
                      document.getElementById("channellistId").options.add(option); 
                  }
               else{
                           option = new Option("暂无频道");
                           document.getElementById("channellistId").options.add(option);
                  }
                     }
              );    
       }
       function fillCategory(chid,bid){
              document.getElementById("categoryId").options.length=1;
              var url = "/book/getAjaxBookCategoryListByChannelID.action";
              var cid = 0;
              if(chid > 0){
                     cid = chid;
              }
              else{
                     cid = document.getElementById("channellistId").value;
              }
              $.getJSON(url,{channelID:cid,ran:Math.random()}, function(json){
        //参数为频道ID及随机数,function(json)为回调函数,其中json为取到的返回数据
                       if(json.strAjaxCategory.length > 0){
                                   var obj = .('(' + json.strAjaxCategory + ')');//json文本转化为json对象,以便于遍历
                                   $.each(obj,function(i,n){  //jquery中的遍历方法,
                                 option = new Option(n,i);
                                 if(i==bid)option.selected=true;
                                document.getElementById("categoryId").options.add(option);
                             });
                                  option = new Option("全部分类","-3");
                                  if(bid ==-3)option.selected=true;
                                  document.getElementById("categoryId").options.add(option);
                                  //jquery的方法为:$(# categoryId)[0].options.add(option);
                  }
                  else{
                           if(cid == 999){
                                  option = new Option("全部分类","-1");
                                  document.getElementById("categoryId").options.add(option);                              
                           }
                           else{
                                  option = new Option("暂无分类");
                                  document.getElementById("categoryId").options.add(option);
                           }
                  }
                     }
              );           
       }
 
       function fillSelect(chid,cid){
              fillChannel(chid);
              fillCategory(chid,cid);
       }
</.>
<body <s:if test="bookCategory.bookchannelId >0">onLoad="fillSelect(<s:property value="bookCategory.bookchannelId"/>,<s:property value="bookCategory.id"/>);"</s:if><s:if test="bookCategory==null">onLoad="fillChannel(0);"</s:if>>
原创粉丝点击