DWR第一篇之入门示例

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

DWR第一篇之入门示例

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

 <dependency>
<groupId>org.directwebremoting</groupId>
<artifactId>dwr</artifactId>
<version>3.0.1-RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>

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

 <!-- 配置dwr请求的servlet -->
<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>

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

 package com.skyer.servlet;

 public class CoreServlet {
public void sayHello() {
System.out.println("Hello World!");
} public String getHello(String name) {
return "Hello " + name;
}
}

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

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>dwr_demo</title>
<script type='text/javascript' src='dwr/engine.js'></script>
<script type='text/javascript' src='dwr/util.js'></script>
<script type='text/javascript' src='dwr/interface/CoreServlet.js'></script>
</head> <body>
<input type="button" value="发送" onclick="sayHello();">
<br>
<input type="text" id="getHello">
<br>
<input type="button" value="发送" onclick="getHello();">
<br>
<input type="text" id="getHelloValue">
</body>
<script type="text/javascript">
function sayHello() {
CoreServlet.sayHello();
}
function getHello() {
var name = dwr.util.getValue("getHello");
CoreServlet.getHello(name, function(data) {
dwr.util.setValue("getHelloValue", data);
});
}
</script>
</html>

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

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

上一篇:hdu1548 A strange lift(bfs 或Dijkstra最短路径)


下一篇:使用node.js生成excel报表下载(excel-export express篇)