今天试着用dwr搭建了一个小例子:
从官方网站下载dwr.jar包。
新建项目dwrTest,然后将dwr.ja放在你 webapp 的 WEB-INF/lib目录下。
编辑配置文件
1.在WEN-INF/下新建web.xml文件
- <?xmlversion="1.0"encoding="ISO-8859-1"?>
- <!DOCTYPEweb-appPUBLIC
- "-//SunMicrosystems,Inc.//DTDWebApplication2.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>
- <url-pattern>/dwr/*</url-pattern>
- </servlet-mapping>
- </web-app>
2.在WEN-INF/下新建web.xml文件
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEdwrPUBLIC"-//GetAheadLimited//DTDDirectWebRemoting3.0//EN""http://getahead.org/dwr/dwr30.dtd">
<dwr>
<allow>
<createcreator="new"javascript="helloservice">
<paramname="class"value="com.dwr.service.HelloWorld"/>
</create>
</allow>
</dwr>
3.编写 HelloWorld
- packagecom.dwr.service;
- publicclassHelloWorld{
- publicStringsayHello(Stringname){
- 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;
- <%@pagelanguage="java"contentType="text/html;charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <Metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
- <title>Inserttitlehere</title>
- <scripttype='text/javascript'src='/dwjTest/dwr/engine.js'></script>
- <scripttype='text/javascript'src='/dwjTest/dwr/interface/helloservice.js'></script>
- <scripttype='text/javascript'src='/dwjTest/dwr/util.js'></script>
- <scripttype="text/javascript">
- functionfirstDwr(){
- helloservice.sayHello("adsf",callBackHello);
- }
- functioncallBackHello(data){
- alert(data);
- </script>
- </head>
- <body>
- <inputtype="button"name="button"value="测试"onclick="firstDwr()">
- </body>
- </html>