`
robin35java
  • 浏览: 20621 次
  • 性别: Icon_minigender_2
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

Struts 2与AJAX(第二部分)

阅读更多
http://www.35java.com/zhibo/forum.php?mod=viewthread&tid=370&extra=page%3D3
        更多<s:tree />            在Struts 2的showcase中有两个<s:tree />的例子,分别是静态树与动态树。所谓的静态树即是在编写JSP代码时通过<s:treenode        />生成树节点。我的上一篇文章的例子就是一个典型的静态树。而动态树则是在程序运行期间,Struts 2 运行时(Runtime)根据程序中的数据动态创建树节点。虽然在两个例子中<s:tree        />的theme属性都为“ajax”,但是从严格意义上来说,这两种树都不属于AJAX树,因为它们都是在输出页面时将全部节点加载到其中,而不是在父节点展开时通过XHR(XMLHttpRequest)获取节点数据。
            动态树            下面我们先看一下动态树的例子,接着再一步步地将其改造为名副其实的AJAX 树。下例将会把WEB应用程序的目录树展现在JSP页面中。因此,我需要先包装一下java.io.File        类,代码如下:
            package tutorial;
               
                import java.io.File;
                       
                        public
        class FileWrapper                     {
                                           private                        File file;
                       
                                                   public                            FileWrapper(String path)                                 {
                                                                                       file =
new                                                File(path);
                                                                                                   }
                                                                                                          
                                                                                                           public                                                        FileWrapper(File file)                                                             {
                                                                                                                                               this.file                                                                    = file;
                                                                                                                                                   }
                                                                                                                                                          
                                                                                                                                                           public                                                                                String getId()                                     {
                                                               return
"file_"
                        + file.hashCode();
                                                           }
                                                                  
                                                                   public                                    String getName()                                         {
                                                                                                       return file.getName();
                                                                                                           }
                                                                                                                  
                                                                                                                   public                                                            String getAbsolutePath()                                                                 {
                                                                                                                                                       return file.getAbsolutePath();
                                                                                                                                                           }
                                                                                                                                                                  
                                                                                                                                                                   public                                                                                    FileWrapper[] getChildren()                                     {
                                                               File[] files = file.listFiles();
                                                                       if(files                                !=
                        null
&& files.length                         >
0)                                 {
                                                                                           int length = files.length;
                                                                                                           FileWrapper[] wrappers                                     =
                                        new FileWrapper[length];
                                                                                                   for(int                                                    i =
                                    0; i < length;                                     ++i)                                         {
                                                                                                               wrappers                                                     =
new FileWrapper(files);
                                                                                                                           }
                                                                                                                                   return wrappers;
                                                                                                                                       }
                                                                                                                                               return
new                                                                            FileWrapper[0];
                                                                                                                                                                   }
                                                                                    }
    清单1 src/tutorial/FileWrapper.java            之所以需要对File类进行如此包装,是因为<s:tree />用于动态树时,rootNode、nodeIdProperty、nodeTitleProperty        和 childCollectionProperty等属性都必填的。
            然后是Action类的代码如下:
            package tutorial;
               
                import javax.servlet.http.HttpServletRequest;
                       
                        import org.apache.struts2.interceptor.ServletRequestAware;
                               
                                import com.opensymphony.xwork2.ActionSupport;
                                       
                                        public
        class DynamicTreeAction        extends ActionSupport        implements ServletRequestAware                    {
                                           private
static
                final
long serialVersionUID                 =
                    1128593047269036737L;
                                                  
                                                   private                            HttpServletRequest request;
                                                           private                                FileWrapper root;
                               
                                                                   public
void setServletRequest(HttpServletRequest                                    request)                                         {   
                                                                                                       this.request                                                = request;
                                                                                                           }
                                                                                                                  
                                                                                                                   public                                                            FileWrapper getRoot()                                                                 {
                                                                                                                                                       return root;
                                                                                                                                                           }
                                                                                                                                                                  
                                                                                                                                                                   @Override
                                                                                                                                                                   public                                                                                    String execute()                                     {
                                                               root =
new                                    FileWrapper(request.getSession().getServletContext().getRealPath("/"));                                                  
                                                                                               return SUCCESS;
                                                                                                   }
                                                    }
    清单2 src/tutorial/DynamicTreeAction.java            上述代码取得WEB应用程序的根目录的绝对路径后,初始化FileWrapper对象root。该对象将为JSP页面的<s:tree />的根节点。如下代码所示:
            <%@ 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 - More Tree</title>
<s:head theme="ajax" debug="true"
        />
<script type="text/javascript">
                            /* <![CDATA[         */
                function treeNodeSelected(arg)                    {
                                    alert(arg.source.title         + ' selected');
                        }
                       
                                        function treeNodeExpanded(arg)                    {
                                    alert(arg.source.title         + ' expanded');
                        }
                       
                                        function treeNodeCollapsed(arg)                    {
                                    alert(arg.source.title         + ' collapsed');
                        }
                       
                        dojo.addOnLoad(function()                    {               
                                    var                            t = dojo.widget.byId('appFiles');
                                                dojo.event.topic.subscribe(t.eventNames.expand,                                treeNodeExpanded);               
                                                dojo.event.topic.subscribe(t.eventNames.collapse,                                treeNodeCollapsed);
                                               
                                                        var s                 = t.selector;                                  
                                    dojo.event.connect(s, 'select',                    'treeNodeSelected');
                                });
                                                    /* ]]>         */
</script>
</head>
<body>
<h2>
                                                        Dynamic Tree Example
                                                    </h2>
<div         style="float:left;            margin-right: 50px;">
<s:tree id="appFiles" theme="ajax" rootNode="root"
                                                    nodeTitleProperty="name" nodeIdProperty="id"
                                                                childCollectionProperty="children"
        />
</div>
</body>
</html>
    清单3 WebContent/Tree.jsp            因为<s:tree />的treeCollapsedTopic和treeExpandedTopic属性都没有起作用,所以如果我们想要监听这两个事件,就必须使用上述代码的方法。
            最后是struts.xml配置文件:
            <?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="struts-default">
<action name="DynamicTree" class="tutorial.DynamicTreeAction">
        <result>Tree.jsp</result>
</action>
</package>
</struts>
    清单4 src/struts.xml            发布运行应用程序,在浏览器地址栏中键入http://localhost:8080/Struts2_Ajax2/DynamicTree.action,有如下图所示页面:
           
        图1 动态树示例   
            AJAX 树            正如我在文章开头所说,Struts 2所提供的静态树和动态树都不是严格意义上的AJAX树。下面就让我们来实现一个如假包换的AJAX树。首先要说明的是,Struts        2的<s:tree />默认是不支持这种按需加载数据的AJAX树。不过因为它是基于Dojo的树控件(Widget)所以要扩展也很方便。
            Dojo 通过名为“TreeRPCController”的控件实现 AJAX 树,它会监听被控制树的事件。当发生展开节点的事件时,TreeRPCController就会向URL发送XHR请求,该URL由TreeRPCController的RPCUrl        属性定义。XHR请求格式类似如下格式:
            http://localhost:8080/Struts2_Ajax2/AjaxTree.action?action=getChildren&data={"node":{"widgetId":"file_226092423","objectId":"C:\\Program                                                Files\\Tomcat 5.5\\webapps\\Struts2_Ajax2","index":0,"isFolder":true},"tree":{"widgetId":"appFiles","objectId":""}}&dojo.preventCache=1182913465392
    清单5 XHR样本            显而易见,请求中包含三个参数,分别是action为“getChildren”(固定值),data一个包含当前节点与树信息的JSON串和dojo.preventCache随机串,用于缓存不同节点的请求响应(父节点只会在第一次被展开时到服务器端加载数据,之后都是从浏览器的缓存中读取数据,可以提高应用程序性能)。
            首先我要先写一个加载树节点数据的Action类,代码如下:
            package tutorial;
               
                import java.util.Map;
                       
                        import com.googlecode.jsonplugin.JSONExeption;
                                import com.googlecode.jsonplugin.JSONUtil;
                                       
                                        public
        class AjaxTreeAction        extends DynamicTreeAction                    {
                                           private
static
                final
long serialVersionUID                 =
                    3970019751740942311L;
                       
                                                   private                            String action;
                                                           private                                String data;
                                                                   private                                    FileWrapper[] wrappers;
                                   
                                                                           public
void setAction(String                                        action)                                             {
                                                                                                               this.action                                                    = action;
                                                                                                                   }
                                                                                                                          
                                                                                                                           public
void setData(String                                                                data)                                                                     {
                                                                                                                                                               this.data                                                                            = data;
                                                                                                                                                                   }
                                                                                   
                                                                                                                                                                           public                                                                                        FileWrapper[] getWrappers()                                     {
                                                               return wrappers;
                                                                   }
                                   
                                                                           @Override
                                                                           public                                        String execute()                                             {
                                                                                                               if("getChildren".equals(action))                                                                                                     {
                                                                                                                                   try
                                                                    {
                                                                                                                                                                       Object o                                                                                 = JSONUtil.deserialize(data);
                                                                                                                                                                                       String path                                                                         = ((Map) ((Map) o).get("node")).get("objectId").toString();
                                                                                                                                                                                               wrappers                                                                         =
                                                                            new FileWrapper(path).getChildren();
                                                                                                                                                                           }
catch (JSONExeption                                                                                    e)                                                                                         {
                                                                                                                                                                                                               e.printStackTrace();
                                                                                                                                                                                                           }
                                                                                                                                                                                                                   return
"ajax";
                                                                                                                                                                                                                                       }   
                                                                                                                                                                                                                                               return
                                                super.execute();
                                                                                                           }
                                                        }
    清单6 src/tutorial/AjaxTreeAction.java            上述代码可能需要解释一下:
   
分享到:
评论

相关推荐

    第10章 Struts 2与Ajax.ppt

    第10章 Struts 2与Ajax.ppt

    AJAX和struts2传递JSON数组

    **二、后端Struts2 Action接收JSON** 在Struts2的Action中,我们需要一个字段来接收这个JSON数组。由于Java没有内置的JSON类,我们可以使用第三方库如Gson或Jackson来帮助解析JSON。这里以Gson为例: 1. 首先,在...

    基于Struts 2 Ajax实现的Login应用

    Struts 2是Apache Struts的第二个版本,它是一个用于开发Java Web应用程序的开源框架。该框架提供了强大的MVC(模型-视图-控制器)架构支持,使得开发者能够更方便地构建可维护、结构清晰的应用程序。Struts 2具有...

    第3章_Struts2标签库详解与AJAX技术应用.rar

    5. `remote`标签:Struts2提供了`&lt;s:remote&gt;`标签来创建远程调用,它可以与服务器进行异步通信,并在响应后更新指定的DOM元素。 6. JSON(JavaScript Object Notation):在AJAX请求中,JSON是一种常见的数据交换...

    ajax+struts2.0+jsp下拉列表级联

    首先,AJAX(Asynchronous JavaScript and XML)是一种在不刷新整个页面的情况下与服务器交换数据并更新部分网页的技术。在这里,AJAX将用于异步地获取和更新下拉列表的数据,提高用户体验,减少网络传输的开销。 ...

    Struts2+ajax+json异步上传图片回显

    总结来说,"Struts2+ajax+json异步上传图片回显"是一个综合运用前端与后端技术的实践,它涉及到Struts2的文件上传处理、Ajax的异步通信以及JSON数据的交互,为用户提供了一个流畅的图片上传体验。

    Struts2整合jQuery实现Ajax功能

    #### 三、Struts2与jQuery的整合 在Struts2项目中集成jQuery可以显著提高用户体验。下面我们将详细介绍如何在Struts2中引入jQuery,并通过一个具体的示例来演示如何利用jQuery实现Ajax功能。 ##### 3.1 引入jQuery ...

    Struts与Ajax.rar

    在提供的PDF文档《Struts 2与AJAX(第一部分)、(第二部分)、(第三部分)》中,可能涵盖了如何配置Struts2框架以支持Ajax,以及如何在Action中处理Ajax请求,如何使用Ajax标签库创建Ajax请求,如何处理和展示Ajax...

    第3章 Struts2标签库详解与AJAX技术应用大型门户网站是这样炼成的

    大型门户网站是这样炼成的,本书详细介绍了以JSP 2、Struts 2、Spring 2.5、Hibernate 3.2、AJAX等主流JavaEE技术进行优化组合开发高性能大型门户网站的实践经验。针对读者的不同学习阶段,共分技术篇、实践篇与部署...

    Struts AJAX文件上传

    AJAX则是一种在客户端和服务器之间进行异步数据交换的技术,它通过JavaScript与XML的组合,实现在不重新加载整个网页的情况下更新部分网页内容。然而,实际的AJAX操作通常不再局限于XML,它可以处理任何形式的文本...

    Strut2.0 与AJAX(第三部分)

    ### Struts2.0与AJAX(第三部分)—— 使用DWR实现AJAX表单校验 #### 一、引言 随着Web技术的发展,AJAX作为一种新兴的技术被广泛应用于现代Web开发中,使得Web应用更加高效且用户体验更好。Struts2作为一款流行的...

    struts2+json+jquery实现ajax数据的存取

    Struts2通过Action类和配置文件来定义请求映射,支持拦截器机制,能方便地集成各种插件和第三方库,例如JSON支持。 **2. JSON (JavaScript Object Notation)** JSON是一种轻量级的数据交换格式,易于人阅读和编写,...

    jquery的ajax传json对象数组到struts2的action

    在Web开发中,jQuery的AJAX功能经常被用于与服务器进行异步数据交换,而Struts2作为一款流行的Java Web框架,提供了处理前端请求的能力。本文将深入探讨如何使用jQuery的AJAX方法发送JSON对象数组到Struts2的Action...

    hibernate+struts2+ajax的网上商城

    "struts2"是Struts框架的第二个版本,是一个用于构建企业级Web应用程序的开放源码MVC框架。它通过Action、Result和Interceptor等组件,实现了请求处理和业务逻辑的分离,增强了应用的灵活性和可扩展性。"ajax"即...

    Struts2 + jQuery+JSON 实现ajax

    本篇文章介绍如何利用Struts2框架结合jQuery与JSON来构建一个简单的Ajax功能。 #### 一、环境搭建 1. **引入Struts2的JSON插件** 描述中提到的第一步是将Struts2的JSON插件加入到Web项目的lib目录下。这一步非常...

    ajax无页面刷新验证、struts结构+ajax+验证码jsp页面

    本主题主要关注的是如何在Struts框架下结合Ajax实现无页面刷新的验证码验证功能,以及在JSP页面中处理验证码的部分。 首先,我们来理解一下Struts框架。Struts是一种基于MVC(Model-View-Controller)设计模式的...

    网络在线考试系统(Struts1.2+Ajax+SQLServer2000实现)

    (2)本系统共分为二种操作权限,分别为学生和管理员。  考生:注册和登录系统、在线考试、查询成绩以及修改个人资料。  管理员:对考生信息、课程信息、考题信息和考生成绩信息等进行管理。 (3)如果您忘登录...

    struts2API文档

    10. **第十章:Struts2与AJAX** - 描述Struts2与Ajax的集成,实现页面的部分刷新。 11. **第十一章:Struts2与Spring集成** - 讨论如何将Struts2与Spring框架结合,实现依赖注入和事务管理。 12. **第十二章:Struts...

    Struts2权威指南完整版

    第二版删除了第一版中第18章的内容(Struts 2和Struts 1整合部分),全面介绍了Struts 2.1新增的Convention和REST支持。《Struts 2.1权威指南》最后配备的两个常用的实例也都升级为基于Struts 2.1运行,读者可通过这两...

    [Struts 2权威指南--基于WebWork核心的MVC开发(高清完整版) 1/12

    第1章 Struts 2概述,第2章 Struts 2下的HelloWorld,第3章 Struts 2基础,第4章 深入Struts 2,第5章 Struts 2的类型转换,第6章 文件的上传和下载.,第7章 Struts 2的拦截器,第8章 Struts 2的输入校验,9.2 ...

Global site tag (gtag.js) - Google Analytics