框架简介:DWR(Direct Web Remoting)
是一个用于改善web页面与Java类交互的远程服务器端Ajax开源框架,可以帮助开发人员开发包含AJAX技术的网站。它可以允许在浏览器里的代码使用运行在WEB服务器上的JAVA函数,就像它就在浏览器里一样。
本Demo实现的基本功能:
Demo构建流程:
1.新建Web工程
2.导入jar包:commons-logging-x.x.x.jar和dwr3.0.jar
3.在web.xml中加入DWR使用能力:
- <servlet>
- <servlet-name>dwr-invoker</servlet-name>
- <servlet-class>uk.ltd.getahead.dwr.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>allowScriptTagRemoting</param-name>
- <param-value>true</param-value>
- </init-param>
- </servlet>
- <servlet-mapping>
- <servlet-name>dwr-invoker</servlet-name>
- <url-pattern>/dwr/*</url-pattern>
- </servlet-mapping>
4.在src中新建类MessagePush:
- packagesugar.dwr;
- publicclassMessagePush{
- publicvoidsend(Stringstr){
- System.out.println(str);
- }
- }
5.与web.xml同级目录下创建dwr.xml,用来配置js函数与java代码的映射关系:
- <?xmlversion="1.0"encoding="UTF-8"?>
- <!DOCTYPEdwrPUBLIC"-//GetAheadLimited//DTDDirectWebRemoting3.0//EN""http://getahead.org/dwr/dwr30.dtd">
- <dwr>
- <allow>
- <createcreator="new"javascript="messagePush">
- <paramname="class">sugar.dwr.MessagePush</param>
- </create>
- </allow>
- </dwr>
6.在index.jsp中写入js逻辑(该处使用到jquery,请自行添加):
- <%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
- <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
- <html>
- <head>
- <title>DWR</title>
- <scripttype="text/javascript"src="js/jquery-1.8.3.js"></script>
- <scripttype="text/javascript"src="dwr/util.js"></script>
- <scripttype="text/javascript"src="dwr/engine.js"></script>
- <scripttype="text/javascript"src="dwr/interface/messagePush.js"></script>
- </head>
- <body>
- <tableborder="0">
- <tr>
- <td><inputid="content"type="text"/></td>
- <td><inputid="send"type="button"value="send"/></td>
- </tr>
- </table>
- <scripttype="text/javascript">
- $("#send").click(function(){
- varcontent=$("#content").val();
- messagePush.send(content);
- });
- </script>
- </body>
- </html>
测试结果: