这几天一直在看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文件中:
- <?xmlversion="1.0"encoding="UTF-8"?>
- <web-appversion="3.0"xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http:
- http:
- <display-name></display-name>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
-
- <servlet>
- <display-name>DWRServlet</display-name>
- <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>
- </servlet>
- <servlet-mapping>
- <url-pattern>/dwr/*</url-pattern>
- </servlet-mapping>
- </web-app>
6. 在src目录下面创建我们的服务类DWRService.java
packageorg.piedra.dwr.service;
publicclassDWRService{
publicStringsayHello(Stringname)throwsException{
if("error".equals(name)){
thrownewException();
}
return"dwrsayhelloto"+name;
}
7. 在WEB-INF目录下面创建xml文件,命名为dwr.xml,内容如下:
<!DOCTYPEdwrPUBLIC
"-//GetAheadLimited//DTDDirectWebRemoting3.0//EN"
"http://getahead.org/dwr/dwr30.dtd">
<dwr>
<allow>
<createcreator="new"javascript="JDate">
<paramname="class"value="java.util.Date"/>
</create>
<createcreator="new"javascript="DwrService">
<paramname="class"value="org.piedra.dwr.service.DWRService"/>
</allow>
</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的时候,执行的是
onclick='DwrService.sayHello(objectEval($("p00").value),reply0);'
这下我们明白了,它是将我们输入的值传入objectEval然后设置回调函数为replay0。这样,当调用成功的时候,就会执行回调函数replay0了。
<html>
<head>
<title>DWRTest</title>
<!--Thesepathsuse..sothattheystillworkbehindapathmappingproxy.Thefullyqualifiedversionismorecutandpastefriendly.-->
<scripttype='text/javascript'src='../engine.js'></script>
<scripttype='text/javascript'src='../util.js'></script>
<scripttype='text/javascript'src='../interface/DwrService.js'></script>
<scripttype='text/javascript'>
functionobjectEval(text)
{
//syntaxbecauseitthinksthat{and}surroundablockandnotanobject
//Sowewrapitinanarrayandextractthefirstelementtogetaround
//this.
//Thiscodeisonlyneededforinterpretingtheparameterinputfields,
//soyoucanignorethisfornormaluse.
//Theregex=[startofline][whitespace]{[stuff]}[whitespace][endofline]
text=text.replace(/n/g,'');
text=text.replace(/r/g,85); font-weight:bold">if(text.match(/^s*{.*}s*$/))
text='['+text+'][0]';
returneval(text);
</script>
<style>
input.itext{font-size:smaller;background:#E4E4E4;border:0;}
input.ibutton{font-size:xx-small;border:1pxoutset;margin:0px;padding:0px;}
span.reply{background:#ffffdd;white-space:pre;}
span.warning{font-size:smaller;color:red;}
</style>
</head>
<bodyonload='dwr.util.useLoadingMessage()'>
<h2>MethodsFor:DwrService(NewCreatorfororg.piedra.dwr.service.DWRService)</h2>
Tousethisclassinyourjavascriptyouwillneedthefollowingscriptincludes:
<pre>
<scripttype='text/javascript'src='<ahref='/dwr/dwr/engine.js'>/dwr/dwr/engine.js</a>'></script>
<scripttype='text/javascript'src='<ahref='/dwr/dwr/interface/DwrService.js'>/dwr/dwr/interface/DwrService.js</a>'></script>
</pre>
Inadditionthereisanoptionalutilityscript:
<scripttype='text/javascript'src='<ahref='/dwr/dwr/util.js'>/dwr/dwr/util.js</a>'></script>
RepliesfromDWRareshownwithayellowbackgroundiftheyaresimpleorinanalertboxotherwise.<br/>
TheinputsareevaluatedasJavascriptsostringsmustbequotedbeforeexecution.
<li>
sayHello(<inputclass='itext'type='text'size='10'value='""'id='p00'title='Willbeconvertedto:java.lang.String'/>);
<inputclass='ibutton'type='button'onclick='DwrService.sayHello(objectEval($("p00").value),reply0);'value='Execute'title='CallsDwrService.sayHello().Viewsourcefordetails.'/>
varreply0=function(data)
if(data!=null&&typeofdata=='object')alert(dwr.util.toDescriptiveString(data,2));
elsedwr.util.setValue('d0',dwr.util.toDescriptiveString(data,0)">1));
<spanid='d0'class='reply'></span>
</li>
</ul>
<h2>OtherLinks</h2>
[list]
[*]Backto<ahref='/dwr/dwr/'>moduleindex</a>.
[/list]
<div>
<h2>FixingIssues</h2>
<h3><aname="missingConverter">Warning:NoConverterforXXX.</a></h3>
dwr.xmldoesnothaveanallowentrythatenablesconversionofthistypeto
Javascript.ThemostcommoncauSEOfthisproblemisthatXXXisajavabean
andbeanmarshallinghasnotbeenenabled.Beanmarshallingisdisabledby
defaultforsecurityreasons.
Toenablemarshallingforagivenbeanaddthefollowinglinetotheallow
sectionofyourdwr.xmlfile:
<convertconverter="bean"match="XXX"/>
Itisalsopossibletoenablemarshallingforanentirepackageorhierachy
ofpackagesusingthefollowing:
<convertconverter="bean"match="package.name.*"/>
<h3><aname="overloadedMethod">Warning:overloadedmethodsarenotrecommended</a></h3>
Javascriptdoesnotsupportoverloadedmethods,sothejavascriptfile
generatedfromclasswillcontaintwomethodsthesecondofwhichwill
replacethefirst.Thisisprobablynotwhatyouwanted.
ItisbesttoavoidoverloadedmethodswhenusingDWR.
<h3><aname="excludedMethod">Warning:methodName()isexcluded:</a></h3>
Themethodsmaybeexcludedexplicitlywithan<exclude>elementin
dwr.xmlorexcludedimplicitlybynotbeingmentionedinan<include>
element.Orthemethodmaybedefinedin<code>java.lang.Object</code>-
methodsdefinedheremaynotbeexported.
Ifmethodsareexcludedusing<include>or<exclude>thenno
JavaScriptproxywillbegenerated.Toallowtestingofmethodsthatshould
notbeaccessible,addaninit-paramtoWEB-INF/web.xmlwiththename/value
allowImpossibleTests=true.
</div>
</body></html>
9. 通过上面的分析,我们已经知道dwr是如何调用的了。就这样,在我们创建的web项目中的index.jsp中编写我们的调用代码:将
<scripttype='text/javascript'src='/dwr/dwr/engine.js'></script>
<scripttype='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代码如下:
<%@pagelanguage="java"import="java.util.*"pageEncoding="ISO-8859-1"%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<scripttype='text/javascript'
src='${pageContext.request.contextPath}/dwr/engine.js'></script>
src='${pageContext.request.contextPath}/dwr/interface/DwrService.js'></script>
<scripttype='text/javascript'src='${pageContext.request.contextPath}/dwr/util.js'></script>
varreply=function(data){
alert(data);
<body>
<scripttype="text/javascript">
DwrService.sayHello("lwb",{
callback:reply,
errorHandler:function(message){alert("error:"+message);}
});
</body>
</html>
访问:http://localhost:8080/dwr/index.jsp 现象如下:
10. 最后附上我项目的目录结构:源码就不附上了,你自己操作一遍,将让你受益更多。
继续学习、、、 谢谢阅读! (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|