简化ajax的使用之DWR学习

来源:互联网 发布:淘宝网如何货到付款 编辑:程序博客网 时间:2024/05/10 18:32
这几天一直在看web service 和 axis2 。感觉这趟水太浑,太深,整个脑袋瓜晕晕的。不过还行,也算是进步了。正如某校长在毕业典礼上的致辞说过“人生就像高压锅。压力大了,自然就熟了”。我觉得挺在理的,但是大家都明白,压力也不能太大,不然就要发生爆炸事件了。所以呢。我今天就看了下DWR,换换口味。我觉得如果按照官方文档也是蛮简单的。http://directwebremoting.org/dwr/introduction/getting-started.html 

DWR就是要简化ajax的调用。说白了也就是在javascript直接用配置的java类调用,但是调用的返回值要在回调函数中获得。
 

该文按照步骤手把手教你dwr的使用: 
1. 下载dwr的jar包:http://directwebremoting.org/dwr/downloads/index.html 
2. 开发环境myeclipse9.0,当然如果你使用其他版本的myeclipse也行。 
3. 创建一个web项目,命名为dwr 
4. 将我们下载的dwr.jar拷贝到我们项目的WEB-INF/lib目录下。同时由于我们的项目采用的是commons-loggin,所以我们也需要将commons-logging的jar包拷贝到lib目录下 
5. 将dwr的servlet配置到我们的web.xml文件中:
 
Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  5.     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  
  6.     <display-name></display-name>  
  7.     <welcome-file-list>  
  8.         <welcome-file>index.jsp</welcome-file>  
  9.     </welcome-file-list>  
  10.       
  11.     <servlet>  
  12.         <display-name>DWR Servlet</display-name>  
  13.         <servlet-name>dwr-invoker</servlet-name>  
  14.         <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>  
  15.         <init-param>  
  16.             <param-name>debug</param-name>  
  17.             <param-value>true</param-value>  
  18.         </init-param>  
  19.     </servlet>  
  20.     <servlet-mapping>  
  21.         <servlet-name>dwr-invoker</servlet-name>  
  22.         <url-pattern>/dwr/*</url-pattern>  
  23.     </servlet-mapping>  
  24.   
  25. </web-app>  


6. 在src目录下面创建我们的服务类DWRService.java
 
Java代码  收藏代码
  1. package org.piedra.dwr.service;  
  2.   
  3. public class DWRService {  
  4.     public String sayHello(String name) throws Exception{  
  5.         if("error".equals(name)) {  
  6.             throw new Exception();  
  7.         }  
  8.         return "dwr say hello to " + name;  
  9.     }  
  10. }  

7. 在WEB-INF目录下面创建xml文件,命名为dwr.xml,内容如下: 
Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE dwr PUBLIC  
  3.     "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"  
  4.     "http://getahead.org/dwr/dwr30.dtd">  
  5. <dwr>  
  6.   <allow>  
  7.   
  8.     <create creator="new" javascript="JDate">  
  9.       <param name="class" value="java.util.Date"/>  
  10.     </create>  
  11.     <create creator="new" javascript="DwrService">  
  12.       <param name="class" value="org.piedra.dwr.service.DWRService"/>  
  13.     </create>  
  14.   
  15.   </allow>  
  16. </dwr>  


8. 在浏览器中输入:http://localhost:8080/dwr/dwr 即可访问到我们的服务: 
 
如果出现上图样式,那么表明我们的服务发布正常了。点击进入DWRService, 


在图中我们发现我们输入的字符串如果是error就会报错。如果我们输入的字符串不是error,那么就会显示dwr say hello to XXX 的界面。 
但是,以上的在页面中我们使用的都是dwr官方帮我们做好的,而我们需要将dwr应用到自己的项目中。这个时候,我们就要看看点击网DWRService后进入的页面的源代码,我们就能够知道dwr是如何利用javascript直接与后台的java应用交互的,从而隐藏了ajax的细节。 
下面是进入DWRService页面后的源代码,我们先找到sayHello的调用入口。我们容易的发现当我们点击按钮execute的时候,执行的是
 
Java代码  收藏代码
  1. onclick='DwrService.sayHello(objectEval($("p00").value), reply0);'  

这下我们明白了,它是将我们输入的值传入objectEval然后设置回调函数为replay0。这样,当调用成功的时候,就会执行回调函数replay0了。 
Java代码  收藏代码
  1. <html>  
  2. <head>  
  3.   <title>DWR Test</title>  
  4.   <!-- These paths use .. so that they still work behind a path mapping proxy. The fully qualified version is more cut and paste friendly. -->  
  5.   <script type='text/javascript' src='../engine.js'></script>  
  6.   <script type='text/javascript' src='../util.js'></script>  
  7.   <script type='text/javascript' src='../interface/DwrService.js'></script>  
  8.   <script type='text/javascript'>  
  9.     
  10.   
  11.   function objectEval(text)  
  12.   {  
  13.     // eval() breaks when we use it to get an object using the { a:42, b:'x' }  
  14.     // syntax because it thinks that { and } surround a block and not an object  
  15.     // So we wrap it in an array and extract the first element to get around  
  16.     // this.  
  17.     // This code is only needed for interpreting the parameter input fields,  
  18.     // so you can ignore this for normal use.  
  19.     // The regex = [start of line][whitespace]{[stuff]}[whitespace][end of line]  
  20.     text = text.replace(/\n/g, ' ');  
  21.     text = text.replace(/\r/g, ' ');  
  22.     if (text.match(/^\s*\{.*\}\s*$/))  
  23.     {  
  24.       text = '[' + text + '][0]';  
  25.     }  
  26.     return eval(text);  
  27.   }  
  28.   
  29.   </script>  
  30.   <style>  
  31.     input.itext { font-size: smaller; background: #E4E4E4; border: 0; }  
  32.     input.ibutton { font-size: xx-small; border: 1px outset; margin: 0px; padding: 0px; }  
  33.     span.reply { background: #ffffdd; white-space: pre; }  
  34.     span.warning { font-size: smaller; color: red; }  
  35.   </style>  
  36. </head>  
  37. <body onload='dwr.util.useLoadingMessage()'>  
  38. <h2>Methods For: DwrService (NewCreator for org.piedra.dwr.service.DWRService)</h2>  
  39. To use this class in your javascript you will need the following script includes:  
  40.   
  41. <pre>  
  42.   <script type='text/javascript' src='<a href='/dwr/dwr/engine.js'>/dwr/dwr/engine.js</a>'></script>  
  43.   <script type='text/javascript' src='<a href='/dwr/dwr/interface/DwrService.js'>/dwr/dwr/interface/DwrService.js</a>'></script>  
  44. </pre>  
  45. In addition there is an optional utility script:  
  46.   
  47. <pre>  
  48.   <script type='text/javascript' src='<a href='/dwr/dwr/util.js'>/dwr/dwr/util.js</a>'></script>  
  49. </pre>  
  50. Replies from DWR are shown with a yellow background if they are simple or in an alert box otherwise.<br/>  
  51. The inputs are evaluated as Javascript so strings must be quoted before execution.  
  52.   
  53. <li>  
  54.   
  55.   
  56.   sayHello(    <input class='itext' type='text' size='10' value='""' id='p00' title='Will be converted to: java.lang.String'/>  );  
  57.   <input class='ibutton' type='button' onclick='DwrService.sayHello(objectEval($("p00").value), reply0);' value='Execute'  title='Calls DwrService.sayHello(). View source for details.'/>  
  58.   <script type='text/javascript'>  
  59.     var reply0 = function(data)  
  60.     {  
  61.       if (data != null && typeof data == 'object') alert(dwr.util.toDescriptiveString(data, 2));  
  62.       else dwr.util.setValue('d0', dwr.util.toDescriptiveString(data, 1));  
  63.     }  
  64.   </script>  
  65.   <span id='d0' class='reply'></span>  
  66.   
  67.   
  68. </li>  
  69. </ul>  
  70. <h2>Other Links</h2>  
  71. [list]  
  72. [*]Back to <a href='/dwr/dwr/'>module index</a>.  
  73.   
  74. [/list]  
  75. <div>  
  76.   
  77. <h2>Fixing Issues</h2>  
  78.   
  79. <h3><a name="missingConverter">Warning: No Converter for XXX.</a></h3>  
  80.   
  81.   dwr.xml does not have an allow entry that enables conversion of this type to  
  82.   Javascript. The most common cause of this problem is that XXX is a java bean  
  83.   and bean marshalling has not been enabled. Bean marshalling is disabled by  
  84.   default for security reasons.  
  85.   
  86.   
  87.   
  88.   To enable marshalling for a given bean add the following line to the allow  
  89.   section of your dwr.xml file:  
  90.   
  91.   
  92. <pre>  
  93. <convert converter="bean" match="XXX"/>  
  94. </pre>  
  95.   
  96.   It is also possible to enable marshalling for an entire package or hierachy  
  97.   of packages using the following:  
  98.   
  99.   
  100. <pre>  
  101. <convert converter="bean" match="package.name.*"/>  
  102. </pre>  
  103.   
  104. <h3><a name="overloadedMethod">Warning: overloaded methods are not recommended</a></h3>  
  105.   
  106.   Javascript does not support overloaded methods, so the javascript file  
  107.   generated from this class will contain two methods the second of which will  
  108.   replace the first. This is probably not what you wanted.  
  109.   
  110.   
  111.   
  112.   It is best to avoid overloaded methods when using DWR.  
  113.   
  114.   
  115.   
  116. <h3><a name="excludedMethod">Warning: methodName() is excluded:</a></h3>  
  117.   
  118.   The methods may be excluded explicitly with an <exclude> element in  
  119.   dwr.xml or excluded implicitly by not being mentioned in an <include>  
  120.   element. Or the method may be defined in <code>java.lang.Object</code> -  
  121.   methods defined here may not be exported.  
  122.   
  123.   
  124.   
  125.   If methods are excluded using <include> or <exclude> then no  
  126.   JavaScript proxy will be generated. To allow testing of methods that should  
  127.   not be accessible, add an init-param to WEB-INF/web.xml with the name/value  
  128.   allowImpossibleTests=true.  
  129.   
  130.   
  131.   
  132. </div>  
  133. </body></html>  


9. 通过上面的分析,我们已经知道dwr是如何调用的了。就这样,在我们创建的web项目中的index.jsp中编写我们的调用代码:将 
Java代码  收藏代码
  1. <script type='text/javascript' src='/dwr/dwr/engine.js'></script>  
  2.  <script type='text/javascript' src='/dwr/dwr/interface/DwrService.js'></script>  

复制到我们的index.jsp中的head部分。我是把第一个/dwr修改成${pageContext.request.contextPath}。这样当我们项目名称改变得时候就不用在来修改index.jsp的源码了。 
然后将上面源码中的objectEval复制到我们的index.jsp中。接着编写我们自己的回调函数replay。最后就是在index.jsp的body部分直接调用DwrService.sayHello 整个index.jsp代码如下:
 
Java代码  收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>  
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  3. <html>  
  4. <head>  
  5. <script type='text/javascript'  
  6.     src='${pageContext.request.contextPath }/dwr/engine.js'></script>  
  7. <script type='text/javascript'  
  8.     src='${pageContext.request.contextPath }/dwr/interface/DwrService.js'></script>  
  9.  <script type='text/javascript' src='${pageContext.request.contextPath }/dwr/util.js'></script>  
  10.   
  11. <script type='text/javascript'>  
  12.     function objectEval(text)  
  13.     {  
  14.         text = text.replace(/\n/g, ' ');  
  15.         text = text.replace(/\r/g, ' ');  
  16.         if (text.match(/^\s*\{.*\}\s*$/))  
  17.         {  
  18.           text = '[' + text + '][0]';  
  19.         }  
  20.         return eval(text);  
  21.     }  
  22.     
  23.     var reply = function(data){  
  24.         alert(data);  
  25.     }  
  26.     
  27.   </script>  
  28. </head>  
  29.   
  30. <body>  
  31.     <script type="text/javascript">  
  32.         DwrService.sayHello("lwb",{  
  33.         callback:reply,  
  34.         errorHandler:function(message) { alert("error : " + message); }  
  35.         });  
  36.     </script>  
  37. </body>  
  38. </html>  

访问:http://localhost:8080/dwr/index.jsp  现象如下: 


10. 最后附上我项目的目录结构:源码就不附上了,你自己操作一遍,将让你受益更多。 

 


继续学习、、、 

谢谢阅读!