DWR第一篇之入门示例

1. 新建maven-web项目,目录结构如下:

2. 在pom.xml里添加dwr所需的依赖

 1 <dependency>
 2     <groupId>org.directwebremoting</groupId>
 3     <artifactId>dwr</artifactId>
 4     <version>3.0.1-RELEASE</version>
 5 </dependency>
 6 <dependency>
 7     <groupId>commons-logging</groupId>
 8     <artifactId>commons-logging</artifactId>
 9     <version>1.2</version>
10 </dependency>

3.  在web.xml里边添加dwr的servlet配置

1 <!-- 配置dwr请求的servlet -->
2 <servlet>
3     <servlet-name>dwr-invoker</servlet-name>
4     <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
5 </servlet>
6 <servlet-mapping>
7     <servlet-name>dwr-invoker</servlet-name>
8     <url-pattern>/dwr/*</url-pattern>
9 </servlet-mapping>

4. 新建核心控制器类CoreServlet.java(注意:这里只是普通的java类,不是servlet)

 1 package com.skyer.servlet;
 2 
 3 public class CoreServlet {
 4     public void sayHello() {
 5         System.out.println("Hello World!");
 6     }
 7 
 8     public String getHello(String name) {
 9         return "Hello " + name;
10     }
11 }

5. 在WEB_INF根目录下添加dwr.xml文件:

<!DOCTYPE dwr PUBLIC
    "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"
    "http://getahead.org/dwr/dwr30.dtd">

<dwr>
    <allow>
        <create creator="new" javascript="CoreServlet">
            <param name="class" value="com.skyer.servlet.CoreServlet" />
        </create>
    </allow>
</dwr>

6.  新建测试用的jsp页面index.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3     String path = request.getContextPath();
 4     String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9 <head>
10 <base href="<%=basePath%>">
11 
12 <title>dwr_demo</title>
13 <script type='text/javascript' src='dwr/engine.js'></script>
14 <script type='text/javascript' src='dwr/util.js'></script>
15 <script type='text/javascript' src='dwr/interface/CoreServlet.js'></script>
16 </head>
17 
18 <body>
19     <input type="button" value="发送" onclick="sayHello();">
20     <br>
21     <input type="text" id="getHello">
22     <br>
23     <input type="button" value="发送" onclick="getHello();">
24     <br>
25     <input type="text" id="getHelloValue">
26 </body>
27 <script type="text/javascript">
28     function sayHello() {
29         CoreServlet.sayHello();
30     }
31     function getHello() {
32         var name = dwr.util.getValue("getHello");
33         CoreServlet.getHello(name, function(data) {
34             dwr.util.setValue("getHelloValue", data);
35         });
36     }
37 </script>
38 </html>

注意,JSP文件里引入了三个js包,其中engine.js和util.js是dwr里自带的js文件,添加到项目里即可。另外一个CoreServlet.js文件需要自己手动建立,其路径必须在dwr/interface,名称必须和dwr.xml配置文件里的javascript属性一致。下面的js脚本调用了CoreServlet里的方法。

7. 测试(注意:需要JDK1.7及以上)

posted @ 2017-08-30 19:57  我滴个小张张  阅读(243)  评论(0编辑  收藏  举报