什么是DWR?
DWR是一个Open Source的 java项目。DWR可以让JavaScript调用运行在Web服务器里面的JAVA程序。简单一点或者专业一点就是Easy AJAX for JAVA.
官方网站:http://getahead.org/dwr
下面将一步一步的介绍怎么完成一个简单DEMO
开发工具NetBeans IDE 6.0+Apache Tomcat 6.0.14
1、从官方网站下载DWR.jar包(附件中也有)
把他直接放到Apache Tomcat 6.0.14\lib目录下面
2、编写一个Java类如下
package com.test.ajax;
public class DWRTest {
public DWRTest(){
}
public String getMyName(){
return "Hello Ajax";
}
}
3、修改web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="dwr">
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
</web-app>
4、把DRWTest类配置在dwr.xml中,dwr.xml是DWR的配置文件,所有需要在JavaScript中调用的java的类都必须在这个文件中描述 (必须与web.xml同级)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN" "http://www.getahead.ltd.uk/dwr/dwr10.dtd">
<dwr>
<allow>
<create creator="new" javascript="MyTest" scope="application">
<param name="class" value="com.test.ajax.DWRTest"/>
</create>
</allow>
</dwr>
5、编写调用DWRTest类中的getMyName方法的jsp文件
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>DWR - Test Home</title>
<script type='text/javascript' src='dwr/interface/MyTest.js'></script>
<script type='text/javascript' src='dwr/engine.js'></script>
<script type='text/javascript' src='dwr/util.js'></script>
<script language="javascript">
var mycall=function callBack(data){
DWRUtil.setValue("demo1",data);
}
function showMyName(){
MyTest.getMyName(mycall);
}
function clearName(){
demo1.value="";
}
</script>
</head>
<body>
<h1>Ajax Test Page</h1>
<input type="button" value="显示姓名" onclick="javascript:showMyName()">
<input type="button" value="清空" onclick="javascript:clearName()"><br>
<input type="text" id="demo1"><br>
</body>
</html>
6、运行,在浏览器中输入 http://localhost:8084/WebApplication/
附件中是本人做好的例子和dwr.jar包