`
atgoingguoat
  • 浏览: 195814 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

Dwr入门例子(附源代码下载-JBuilder2006工程)完成

    博客分类:
  • java
阅读更多
Dwr+ibatis+oracle9i入门例子(附源代码下载-JBuilder2006工程)
Dwr:用来应用处理事件,可以把JAVA类映射到JS中,由JS直接调用。
ibatis:SQL映射数据处理层,写好SQL,数据库,映射得到数据库中的数据。
oracle:那就是数据库了。

从哪里开始写呢?乱写吧。
先搞个效果图吧:



再介绍下LIB包:


classes12.jar 数据驱动包
commons-beanutils.jar
commons-logging.jar
apache库,我只用了数据类转换时用它。

log4j-1.2.14.jar  日志打印包
ibatis-sqlmap-2.jar,ibatis-dao-2.jar,ibatis-common-2.jar
IBATIS2 必需包。
dwr.jar DWR 包。
以上包大家就不用到官方去下了,我在附件中上传了。

ibatis 部分,我就不多讲了。我其它的文章里面有。
这里主要讲下 DWR 配置吧。
工程代码结构如图:




先说下DWR 服务类吧》
ResourceServer

package cn.permissions.info.dwr.server;

import cn.permissions.info.vo.*;
import cn.permissions.info.service.*;
import java.util.*;
import cn.permissions.info.domain.*;
import org.apache.commons.beanutils.*;

 
public class ResourceServer {

    public ResourceServer(){

    }
    public static void main(String[] args) {
        ResourceServer service = new ResourceServer();
        try {
             java.util.Map map = service.getPageResourceInfoByMap("", "", "",  0, 0  );
             System.out.println("count = "+map.get("count"));
            //service.delete("47");
            // service.deleteOjb("328");
            //Object obj = service.updateOjb("328","namepp",1,"depict","operid","resid");
           // boolean oxxbj = service.saveObj("",1,"namepxxxxp","depict","operid");
        } catch (Exception ex) {
        }


    }

    /**
     * 分面查询权限资源数据列表
     * @param privilesge_name String 权限名称
     * @param oper_id String   操作类型
     * @param compID String   公司ID
     * @param empID String   操作员ID
     * @param deptID String   操作员所属部门
     * @param startRow int   分面参数
     * @param pageSize int   分面参数
     * @return List
     * @throws Exception
     */
    public Map getPageResourceInfoByMap(String resName,String resDepict,String moduleID, int startRow,
                                      int pageSize) throws
            Exception {
        Map map = new HashMap();
        //
        int count = 0;
        Map map_param = new HashMap();
        map_param.put("resName", resName);
        map_param.put("resDepict", resDepict);
        map_param.put("moduleID", moduleID);
        count = ResourceService.getInstance().getPageResourceInfoCount(map_param);

        map_param.put("startRow", startRow);
        map_param.put("pageSize", pageSize);
        List list = (java.util.List) ResourceService.getInstance().getPageResourceInfoByMap(map_param);

        List voList = new ArrayList();
        Resource info = new Resource();
        ResourceVO objvo = null;
        if (count > 0) {
            for (int i = 0; i < list.size(); i++) {
                info = (Resource) list.get(i);
                objvo = new ResourceVO();
                BeanUtils.copyProperties(objvo, info);
                //System.out.println("@@###"+objvo.getModuleID());
                voList.add(objvo);
            }
        }
        map.put("voList", voList);
        map.put("count", count);
        return map;

    }

    /**
     * 新增权限资源信息
     * pri_name,pri_depict,oper_id,res_id,module_id
     * @return boolean
     */
    public boolean saveInfo(String resName,int moduleID,String resDepict,
                                    String resStandBy1,String resStandBy2) {
        boolean bool = false;

        Resource obj = new Resource();
        obj.setResName(resName);
        obj.setModuleID(moduleID);
        obj.setResDepict(resDepict);
        obj.setResStandBy1(resStandBy1);
        obj.setResStandBy2(resStandBy2);
        obj = ResourceService.getInstance().insertResource(obj);
        if (obj != null) {
            bool= true;
        } else {
            bool= false;
        }
        return bool;
    }

    /**
     * 修改权限资源信息
     *
     **/
    public ResourceVO updateInfo(String resID,String resName,int moduleID,String resDepict,
                                    String resStandBy1,String resStandBy2) {
        ResourceVO objVo = new ResourceVO();
        Resource obj = new Resource();
        obj.setResId(resID);
        obj.setResName(resName);
        obj.setModuleID(moduleID);
        obj.setResDepict(resDepict);
        obj.setResStandBy1(resStandBy1);
        obj.setResStandBy2(resStandBy2);
        try {
            BeanUtils.copyProperties(objVo, obj);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        int result = ResourceService.getInstance().updateResource(obj);
        if (result > -1) {
            //setNameFromeID(objVo);
            return objVo;
        } else {
            return null;
        }
    }

    /**
     * 删除权限资源信息
     * @param priID String
     * @return boolean
     */
    public boolean deleteInfo(String priId) {

        /**删除权限资源信息*/
        int result = ResourceService.getInstance().deleteResource(priId);
        if(result > -1) {
            return true;
        }
        else{
            return false;
        }

    }

}


这跟写其它的JAVA类没有什么区别。
只是要抛出些异常。
然后,主要几个方法的返回值,这个好象是固定的, map,boolean, VO 数据类。

接下来就说下DWR 配置文件吧。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://getahead.org/dwr/dwr20.dtd">
<dwr>
  <allow>
    <create creator="new" javascript="ResourceServer">
      <param name="class" value="cn.permissions.info.dwr.server.ResourceServer" />
    </create>
    <convert converter="bean" match="cn.permissions.info.vo.ResourceVO"/>
  </allow>

  <signatures>
    <![CDATA[
    import java.util.*;
    import cn.permissions.info.vo.*;

    ResourceServer.getPageResourceInfoByMap(String,String,String,int,int);
    ResourceServer.saveInfo(String,int,String,String,String);
    ResourceServer.updateInfo(String,String,int,String,String,String);
    ResourceServer.deleteInfo(String);
    ]]>
  </signatures>

</dwr>



这里定义DWR 服务类及方法,它可以让你的JAVA类在JS中使用;
定义你的数据类,让它可以在JS 使用。


WEB.xml 配置也比较简单
主要是加载 DWR
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
  <display-name>permissions</display-name>
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>cn.permissions.info.filter.EncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>GBK</param-value>
    </init-param>
    <init-param>
      <param-name>contentType</param-name>
      <param-value>text/html; charset=GBK</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <listener>
    <listener-class>org.directwebremoting.servlet.EfficientShutdownServletContextAttributeListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.directwebremoting.servlet.EfficientShutdownServletContextListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>dwr-invoker</servlet-name>
    <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
    <init-param>
      <param-name>debug</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>crossDomainSessionSecurity</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>maxWaitAfterWrite</param-name>
      <param-value>-1</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>dwr-invoker</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
  </servlet-mapping>

  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>

</web-app>




再说JS中的调用吧:

var ResourcesInfoCache = {};//缓存对象
var opreatorStauts = 1;//操作标识,主要是区分新增与修改操作;1.新增;2.修改
var currIndex = -1;//当前索引
var id_del = "";//删除时辅助字段
var id_update = "";//修改时的辅助字段

var res_name;
var module_id;
//var compid = $("compId").value;
/**资源管理JS*/
function init() {
  //alert("fillTable");
    currentPage = 1;
    ResourceServer.getPageResourceInfoByMap('','','',(currentPage-1)*pageSize,pageSize,fillTable);
    dwr.util.useLoadingMessage("正在加载部门信息......");
}

//刷新缓存
function flushCache(data) {
    ResourcesInfoCache = data;
}


//填充表格方法
function fillTable(data) {

    dwr.util.removeAllRows("ResourcesInfoBody");
    var ResourcesInfo = data.voList;
    totalRows = data.count;
    var cellFuncs = [
        function(ResourcesInfo) {return ResourcesInfo.resId; },
        function(ResourcesInfo) {return ResourcesInfo.resName; },
        function(ResourcesInfo) {return ResourcesInfo.resDepict; },
        function(ResourcesInfo) {return ResourcesInfo.moduleName; },
     	function(ResourcesInfo) {}
    ];
    dwr.util.addRows( "ResourcesInfoBody", ResourcesInfo , cellFuncs,{
      rowCreator:function(options) {
      var row = document.createElement("tr");
	if((options.rowIndex%2)==0) {
  	    row.className = "line2";
	}
	else {
  	    row.className = "line3";
	}
        return row;
    },
        cellCreator:function(options) {
          if(options.cellNum==4){
            var td = document.createElement("td");
            td.setAttribute("align","center");
            var thtml = "<a href=\"javascript:deleteInfo('" + options.rowIndex +"','"+ options.rowData.resId + "','" + options.rowData.resName + "');\" class=\"cz\">删除</a>";
		thtml += " | <a href=\"javascript:updateInfo('" + options.rowIndex +"','"+ options.rowData.resId + "','"+ options.rowData.moduleID + "')\" class=\"cz\">修改</a>";
            td.innerHTML = thtml;

              return td;
            } else {
              return document.createElement("td");
            }
        }
    });
    if(totalRows == 0) {
      currentPage = totalRows;
    }
    turnPage();
    flushCache(ResourcesInfo);
}

/**
* 查询资源 queryResourcesInfos var res_name;
var module_id;
**/
function queryInfo() {

    res_name = $("res_name_query").value;
    module_id = $("module_id_query").value;
    ResourceServer.getPageResourceInfoByMap(res_name,'',module_id,(currentPage-1)*pageSize,pageSize,fillTable);

}

/**
* 此方法用途:
* 分页跳转后填充表格数据
**/
function goPage() {
    res_name = $("res_name_query").value;
    module_id = $("module_id_query").value;
    ResourceServer.getPageResourceInfoByMap(res_name,'',module_id,(currentPage-1)*pageSize,pageSize,fillTable);
}


/**
* 新增资源信息
**/
function addInfo(){
    opreatorStauts = 1;
    showDialog("新增资源信息",addhtmlStr,'success');
}

function saveInfo(){
    if(!checkData()) {
        return ;
    }
    //pri_name,pri_depict,oper_id,res_id,module_id

    var res_name = $("res_name").value;
    var res_depict = $("res_depict").value;
    var module_id = $("module_id").value;
    //保存数据
    alert("module_id = "+module_id);
    hideDialog();
    //
    if(opreatorStauts == 1) {
        ResourceServer.saveInfo(res_name,module_id,res_depict,'','',callback);
    }
    else if(opreatorStauts == 2) {
        ResourceServer.updateInfo(id_update,res_name,module_id,res_depict,'','',updateCallback);
    }
}

function callback(msg) {
    var type = "success";
    var value = "新增资源信息成功!";
    if(!msg) {
       value = "新增资源信息失败!";
       type = "error"
    }
    showDialog("新增资源信息",value,type,3);
    init();
}

function updateCallback(msg) {
    var type = "success";
    var value = "修改资源信息成功!";
    if(!msg) {
       value = "修改资源信息失败!";
       type = "error"
    }
    else {
        if(currIndex > -1) {
          ResourcesInfoCache[currIndex] = msg;
          updateFlush(currIndex);
	}
    }
    showDialog("修改资源信息",value,type,2);
    init();
}

function updateInfo(index,id,modleId) {
    opreatorStauts = 2;
    id_update = id;
    var module_id="";
    var ResourcesInfo = ResourcesInfoCache[index];//从缓存中按索引取数据
    var res_name = ResourcesInfo.resName;
    var res_depict = ResourcesInfo.resDepict;
    var res_id = ResourcesInfo.resId;
       module_id = ResourcesInfo.moduleID;
       module_id = modleId;
    showDialog("修改资源信息",addhtmlStr,'success');
    dwr.util.setValue("res_name",res_name);
    dwr.util.setValue("res_depict",res_depict);
    dwr.util.setValue("module_id",module_id);
    currIndex = index;
}

function updateFlush(index) {
    var rowObj = $("ResourcesInfoBody").rows[index];//获得修改行的数据
    var ResourcesInfo = ResourcesInfoCache[index];
    rowObj.cells[0].innerHTML = ResourcesInfo.ip;
    rowObj.cells[1].innerHTML = ResourcesInfo.companyname;
    rowObj.cells[2].innerHTML = ResourcesInfo.companystatic;
}

/**
* 删除部门信息
**/
function deleteInfo(index,id,companyname) {
    id_del = id;
    var valueStr = '<font color="red">"确定要删除 "'+companyname+'",该资源信息吗?"</font>';
    valueStr += '<table><tr><td align="center"><div id="dosubmit" style="height:30px;width:60px;background:url(../../images/dilog_ok.gif) no-repeat;cursor:pointer;" onclick="deleteGo();"></div></td><td align="center"><div id="dosubmit" style="height:30px;width:60px;background:url(../../images/dilog_cancel.gif) no-repeat;cursor:pointer;" onclick="hideDialog();"></div></td></tr></table>';
    showDialog("删除资源信息",valueStr,'success');
}

function deleteGo() {
    ResourceServer.deleteInfo(id_del,deleteCallback);
}

function deleteCallback(msg) {
    var type = "success";
    var value = "删除资源信息成功!";
    if(!msg) {
       value = "删除资源信息失败!";
       type = "error"
    }
    showDialog("删除资源信息",value,type,2);
    init();
}

/**
* 校验方法
**/
function checkData() {
	if(!isNull(document.getElementById("res_name"))) {
		alert("请输入资源信息名称!");
		document.getElementById("res_name").focus();
		return false;
	}
	return true;
}




再说下JSP的展现吧:
<%@page contentType="text/html; charset=GBK"%>
<%@page import="java.util.*"%>

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<link href="../../css/comm.css" type="text/css" rel="stylesheet"/>
<link href="../../css/tablecss.css" type="text/css" rel="stylesheet"/>
<link href="../../css/dialog_box.css" type="text/css" rel="stylesheet"/>
<title>资源管理</title>
</head>


<body onload="init();">
<input type="hidden" name="compID" value="">
<input type="hidden" name="priID" value="">
<input type="hidden" name="empID" value="">
<input type="hidden" name="deptID" value="">
<center>
  <div id="tableValue" style="display:none">
    <form id="form" method="post">
     <table class="tableData" id="tableData" align="center" border="0" cellspacing="1" cellpadding="0">

      <tr>
        <td width="30%" align="right">权限资源名称</td>
        <td align="left">
          <input maxlength="18" size="18" name="res_name" type="text" value=""/>
        </td>
      </tr>
      <tr>
        <td width="30%" align="right">权限资源描述:</td>
        <td align="left">
          <input type="text" name="res_depict" maxlength="18" size="18" value="" />
        </td>
      </tr>

      <tr>
        <td width="30%" align="right">模块选择</td>
        <td align="left">
          <select id="module_id">
          <option value="">--请选择模块--</option>
          
            <option value="1">测试</option>
          
          </select>
        </td>
      </tr>

      <tr>
        <td width="30%"></td>
        <td align="left">
          <br/>
          <div id="dosubmit" style="height:30px;width:60px;background:url(../../images/dilog_ok.gif) no-repeat;cursor:pointer;" onclick="saveInfo();"></div>
        <div id="dosubmit" style="height:30px;width:60px;background:url(../../images/dilog_cancel.gif) no-repeat;cursor:pointer;" onclick="hideDialog();"></div>
        </td>
      </tr>
    </table>
    </form>
  </div>

  <table width="100%" border="0" cellpadding="0" cellspacing="1" class="TableStyle">
    <thead>
      <tr class="tools" align="left">
        <td colspan="8">
          <div id="navigator">资源管理-->资源数据列表</div>
          <div id="btngroup">
            <ul>
              <li class="btn-add"><a href="javascript:addInfo();" class="btn-right">新增</a></li>
              <li class="btn-search"><a href="javascript:queryInfo();" class="btn-right">查询</a></li>
            </ul>
            <div style="float:right;font-size:12px;color:#000">
            资源名称:
            <input class="globalStyle" name="res_name_query" type="text">
            模块选择:
                     <select id="module_id_query">
          <option value="">--请选择模块--</option>
             <option value="1">测试</option>
          </select>
            </div>
          </div>
        </td>
      </tr>
      <tr class="line1">
        <td>序列</td>
        <td>资源名称</td>
        <td>资源说明</td>
        <td>模块名称</td>
        <td align="center">操作</td>
      </tr>
    </thead>
    <tbody id="ResourcesInfoBody"></tbody>
  </table>
  <div id="turn" class="turnpage">  </div>
</center>
<script src="../../js/function.js" type="text/javascript"></script>
<script type='text/javascript' src='<%=request.getContextPath()%>/dwr/interface/ResourceServer.js'></script>
<script type='text/javascript' src='<%=request.getContextPath()%>/dwr/engine.js'></script>
<script type='text/javascript' src='<%=request.getContextPath()%>/dwr/util.js'></script>
<script type='text/javascript' src='<%=request.getContextPath()%>/js/permission_resource.js'></script>
<script type='text/javascript' src='<%=request.getContextPath()%>/js/common.js'></script>
</body>
</html>





其它的,你们自己看代码吧。。
  • 大小: 45.2 KB
  • 大小: 11.4 KB
  • lib.rar (2.6 MB)
  • 描述: Dwr入门例子 LIB 包
  • 下载次数: 28
  • 大小: 48.8 KB
  • dwr.rar (159.3 KB)
  • 描述: Dwr入门例子 源代码下载
  • 下载次数: 31
1
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics