1 将DWR放入你的工程
1) 从官方网站下载dwr.jar包。然后将它放在你webapp的WEB-INF/lib目录下。
2) 将下载的dwr-版本号-src.zip \java\org\directwebremoting内的engine.js和util.js放入WEB应用中,比如js文件夹下。
首先是代码:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<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>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
</web-app>
dwr.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://www.getahead.ltd.uk/dwr/dwr20.dtd">
<dwr>
<allow>
<create creator="new" javascript="service">
<param name="class" value="com.dhcc.Service" />
</create>
</allow>
</dwr>
Service.java
package com.dhcc;
public class Service {
public String sayHello(String yourName) {
return "Hello " + yourName;
}
}
first_dwr.jsp
<%@ page language="java" contentType="text/html; charset=
GBK" pageEncoding="GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>My JSP 'first_dwr.jsp' starting page</title>
<script type='text/javascript' src='js/util.js'></script>
<script type='text/javascript' src='dwr/engine.js'></script>
<script type='text/javascript' src='dwr/interface/service.js'> </script>
<script type="text/javascript">
function firstDwr(){
service.sayHello("June", callBackHello);
}
function callBackHello(data){
alert(data);
}
</script>
</head>
<body>
<input type="button" name="button" value="测试" οnclick="firstDwr()">
</body>
</html>
6、运行,在浏览器中输入 http://localhost:8080/WebApplication/
其中我们会遇到各种问题
1.你的dwr.jar一定要和dwr-版本号-src.zip为一个版本,不然会出现问题。
2.<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://www.getahead.ltd.uk/dwr/dwr20.dtd">
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN" "http://www.getahead.ltd.uk/dwr/dwr10.dtd">
你的dwr.jar是2.X版本可以用第一个,不然需要改一下。
3.这是中文文档给的代码但是会出现问题
<script type='text/javascript' src='js/util.js'></script>
<script type='text/javascript' src='js/engine.js'></script>
<script type='text/javascript' src='dwr/interface/service.js'>
必须将src='js/engine.js'改为src='dwr/engine.js'。
4、dwr项目需要用到commons-logging-版本号.jar这个jar包,这个包是包含在struts的包里面的,下载的话就是去开源网站下载即可。
这就是我第一个DWR遇到的问题。