框架简介:DWR(Direct Web Remoting)
是一个用于改善web页面与Java类交互的远程服务器端Ajax开源框架,可以帮助开发人员开发包含AJAX技术的网站。它可以允许在浏览器里的代码使用运行在WEB服务器上的JAVA函数,就像它就在浏览器里一样。
本Demo实现的基本功能:
点击jsp界面的按钮,通过DWR调用到服务器端的java代码,在控制台打印出jsp输入框中的值
Demo构建流程:
1.新建Web工程
2.导入jar包:commons-logging-x.x.x.jar和dwr3.0.jar
3.在web.xml中加入DWR使用能力:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
< 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:
1
2
3
4
5
6
7
8
|
package sugar.dwr;
public class MessagePush {
public void send(String str){
System. out.println(str);
}
} |
5.与web.xml同级目录下创建dwr.xml,用来配置js函数与java代码的映射关系:
1
2
3
4
5
6
7
8
9
|
<? xml version = "1.0" encoding = "UTF-8" ?>
<! DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://getahead.org/dwr/dwr30.dtd" >
< dwr >
< allow >
< create creator = "new" javascript = "messagePush" >
< param name = "class" >sugar.dwr.MessagePush</ param >
</ create >
</ allow >
</ dwr >
|
6.在index.jsp中写入js逻辑(该处使用到jquery,请自行添加):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<%@ page language= "java" import ="java.util.*" pageEncoding="UTF-8" %> <! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
< html >
< head >
< title >DWR</ title >
< script type = "text/javascript" src = "js/jquery-1.8.3.js" ></ script >
< script type = "text/javascript" src = "dwr/util.js" ></ script >
< script type = "text/javascript" src = "dwr/engine.js" ></ script >
< script type = "text/javascript" src = "dwr/interface/messagePush.js" ></ script >
</ head >
< body >
< table border = "0" >
< tr >
< td >< input id = "content" type = "text" /></ td >
< td >< input id = "send" type = "button" value = "send" /></ td >
</ tr >
</ table >
< script type = "text/javascript" >
$( "#send").click(function(){
var content = $("#content" ).val();
messagePush.send(content);
});
</ script >
</ body >
</ html >
|
说明:jsp文件中必须引入几个js,它们都是隐含存在的,不用考虑它们在哪儿。其中engine.js和util.js是固定的。另外的一个js的名称就是dwr.xml中配置的类名。
测试结果: