今天试着用dwr搭建了一个小例子:
从官方网站下载dwr.jar包。
新建项目dwrTest,然后将dwr.ja放在你 webapp 的 WEB-INF/lib目录下。
编辑配置文件
1.在WEN-INF/下新建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> <servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping> </web-app>
2.在WEN-INF/下新建web.xml文件
<?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="helloservice"> <param name="class" value="com.dwr.service.HelloWorld" /> </create> </allow> </dwr>
3.编写 HelloWorld
package com.dwr.service;
public class HelloWorld {
public String sayHello(String name){
return "HelloWorld"+name;
}
}
4. 测试 DWR 将代码放入应用服务器(比如Tomcat),启动。然后在地址栏输入:http://localhost/dwjTest/dwr
Modules known to DWR:
- helloservice (NewCreator for com.dwr.service.HelloWorld)
然后点击helloservice,会看到刚才写的sayHello()的方法,上面有dwr自动生成的三个js文件
Methods For: helloservice (NewCreator for com.dwr.service.HelloWorld)
To use this class in your javascript you will need the following script includes:
<script type='text/javascript' src='/dwjTest/dwr/engine.js '></script> <script type='text/javascript' src='/dwjTest/dwr/interface/helloservice.js '></script>In addition there is an optional utility script:
<script type='text/javascript' src='/dwjTest/dwr/util.js '></script>Replies from DWR are shown with a yellow background if they are simple or in an alert box otherwise.
sayHello( );
The inputs are evaluated as Javascript so strings must be quoted before execution.
5.创建jsp页面,引入上面的三个js;
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type='text/javascript' src='/dwjTest/dwr/engine.js'></script> <script type='text/javascript' src='/dwjTest/dwr/interface/helloservice.js'></script> <script type='text/javascript' src='/dwjTest/dwr/util.js'></script> <script type="text/javascript"> function firstDwr(){ helloservice.sayHello("adsf",callBackHello) ; } function callBackHello(data){ alert(data); } </script> </head> <body> <input type="button" name="button" value="测试" οnclick="firstDwr()"> </body> </html>